summaryrefslogtreecommitdiffstats
path: root/store/redis.go
blob: 262040d4376cd096f6ad14065b9c39767be947c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.

package store

import (
	l4g "code.google.com/p/log4go"
	"github.com/mattermost/platform/model"
	"github.com/mattermost/platform/utils"
	"gopkg.in/redis.v2"
	"strings"
	"time"
)

var client *redis.Client

func RedisClient() *redis.Client {

	if client == nil {

		addr := utils.Cfg.RedisSettings.DataSource

		client = redis.NewTCPClient(&redis.Options{
			Addr:     addr,
			Password: "",
			DB:       0,
			PoolSize: utils.Cfg.RedisSettings.MaxOpenConns,
		})

		l4g.Info("Pinging redis at '%v'", addr)
		pong, err := client.Ping().Result()

		if err != nil {
			l4g.Critical("Failed to open redis connection to '%v' err:%v", addr, err)
			time.Sleep(time.Second)
			panic("Failed to open redis connection " + err.Error())
		}

		if pong != "PONG" {
			l4g.Critical("Failed to ping redis connection to '%v' err:%v", addr, err)
			time.Sleep(time.Second)
			panic("Failed to open ping connection " + err.Error())
		}
	}

	return client
}

func RedisClose() {
	l4g.Info("Closing redis")

	if client != nil {
		client.Close()
		client = nil
	}
}

func PublishAndForget(message *model.Message) {

	go func() {
		c := RedisClient()
		result := c.Publish(message.TeamId, message.ToJson())
		if result.Err() != nil {
			l4g.Error("Failed to publish message err=%v, payload=%v", result.Err(), message.ToJson())
		}
	}()
}

func GetMessageFromPayload(m interface{}) *model.Message {
	if msg, found := m.(*redis.Message); found {
		return model.MessageFromJson(strings.NewReader(msg.Payload))
	} else {
		return nil
	}
}