forked from gocelery/gocelery
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredis_broker.go
97 lines (89 loc) · 2.24 KB
/
redis_broker.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
package gocelery
import (
"encoding/json"
"fmt"
"sync"
"time"
"github.com/garyburd/redigo/redis"
)
// RedisCeleryBroker is CeleryBroker for Redis
type RedisCeleryBroker struct {
*redis.Pool
queueName string
stopChannel chan bool
workWG sync.WaitGroup
}
// NewRedisPool creates pool of redis connections
func NewRedisPool(host, pass string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", host)
if err != nil {
return nil, err
}
if pass != "" {
if _, err = c.Do("AUTH", pass); err != nil {
c.Close()
return nil, err
}
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
// NewRedisCeleryBroker creates new RedisCeleryBroker
func NewRedisCeleryBroker(host, pass string) *RedisCeleryBroker {
return &RedisCeleryBroker{
Pool: NewRedisPool(host, pass),
queueName: "celery",
}
}
// SendCeleryMessage sends CeleryMessage to redis queue
func (cb *RedisCeleryBroker) SendCeleryMessage(message *CeleryMessage) error {
jsonBytes, err := json.Marshal(message)
if err != nil {
return err
}
conn := cb.Get()
defer conn.Close()
_, err = conn.Do("LPUSH", cb.queueName, jsonBytes)
if err != nil {
return err
}
return nil
}
// GetCeleryMessage retrieves celery message from redis queue
func (cb *RedisCeleryBroker) GetCeleryMessage() (*CeleryMessage, error) {
conn := cb.Get()
defer conn.Close()
messageJSON, err := conn.Do("BLPOP", cb.queueName, "1")
if err != nil {
return nil, err
}
if messageJSON == nil {
return nil, fmt.Errorf("null message received from redis")
}
messageList := messageJSON.([]interface{})
// check for celery message
if string(messageList[0].([]byte)) != "celery" {
return nil, fmt.Errorf("not a celery message: %v", messageList[0])
}
// parse
var message CeleryMessage
json.Unmarshal(messageList[1].([]byte), &message)
return &message, nil
}
// GetTaskMessage retrieves task message from redis queue
func (cb *RedisCeleryBroker) GetTaskMessage() (*TaskMessage, error) {
celeryMessage, err := cb.GetCeleryMessage()
if err != nil {
return nil, err
}
return celeryMessage.GetTaskMessage(), nil
}