/
common.go
104 lines (95 loc) · 2.21 KB
/
common.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"net"
"os"
"path"
"github.com/Sirupsen/logrus"
redisgo "github.com/garyburd/redigo/redis"
)
type Redis struct {
address string
options []redisgo.DialOption
prefix string
master string
}
var (
logger *logrus.Logger
)
func init() {
logrus.SetOutput(os.Stderr)
logger = logrus.StandardLogger()
}
func (redis *Redis) init(discovery *Discovery) error {
host, port, err := net.SplitHostPort(discovery.url.Host)
if err != nil {
host = discovery.url.Host
}
if host == "" {
return fmt.Errorf("RedisServer host is empty: %s", discovery.url.Host)
}
if port == "" {
port = "6379"
}
logger.Debugf("RedisServer info: host->%s, port->%s", host, port)
address := net.JoinHostPort(host, port)
redis.address = address
password, isSet := discovery.url.User.Password()
if isSet {
redis.options = append(redis.options, redisgo.DialPassword(password))
}
prefix, master := path.Split(discovery.url.Path)
if prefix == "" {
return fmt.Errorf("Redis path is empty: %s", discovery.url.Path)
}
if master == "" {
master = "master"
}
redis.prefix = prefix[1:]
redis.master = master
return nil
}
func (redis *Redis) notice(target string, message interface{}) (interface{}, error) {
conn, err := redis.connect()
if err != nil {
return nil, err
}
defer conn.Close()
return conn.Do("PUBLISH", redis.prefix+redis.master+"/"+target, message)
}
func (redis *Redis) watch(advertise string, handle messageHandler, watching chan<- bool, watchoff chan<- bool) (cancelWatch, error) {
conn, err := redis.connect()
if err != nil {
return nil, err
}
psc := redisgo.PubSubConn{Conn: conn}
psc.Subscribe(redis.prefix + advertise)
cancel := func() {
psc.Unsubscribe()
psc.PUnsubscribe()
}
runing := func() {
defer conn.Close()
watching <- true
for {
switch v := psc.Receive().(type) {
case redisgo.Message:
handle(v.Data)
case redisgo.PMessage:
handle(v.Data)
case error:
watchoff <- true
return
}
}
return
}
go runing()
return cancel, nil
}
func (redis *Redis) connect() (redisgo.Conn, error) {
if redis.address == "" {
return nil, fmt.Errorf("Redis not set, setRedis first:%s", redis)
}
return redisgo.Dial("tcp", redis.address, redis.options...)
}