/
redis.go
58 lines (47 loc) · 1.14 KB
/
redis.go
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
package sources
import (
"fmt"
"github.com/go-redis/redis"
"github.com/one-hole/imserver/config"
"github.com/one-hole/imserver/sockets"
)
var redisInstance *RedisSource
var (
pushChannelName = "tenant-websocket"
)
// RedisSource connected to redis & sub the messages
type RedisSource struct {
client *redis.Client
}
// RedisPing send ping message to redis
func RedisPing() error {
_, err := redisInstance.client.Ping().Result()
return err
}
// RedisInstance returns the singleton instance of Redis
func RedisInstance() *RedisSource {
if redisInstance == nil {
redisInstance = newRedisInstance()
}
return redisInstance
}
func newRedisInstance() *RedisSource {
return &RedisSource{
client: redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", config.Redis.Host, config.Redis.Port),
DB: 12,
}),
}
}
// RunRedis will called in goroutines
func RunRedis(manager *sockets.ClientManager, channelName string) {
if "" == channelName {
return
}
pubsub := RedisInstance().client.Subscribe(channelName)
defer pubsub.Close()
ch := pubsub.Channel()
for msg := range ch {
manager.Broadcast <- []byte(msg.Payload)
}
}