-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_backend.go
67 lines (59 loc) · 1.8 KB
/
redis_backend.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
/*
Gocelery is a task queue implementation for Go modules used to asynchronously execute work outside the HTTP request-response cycle. Celery is an implementation of the task queue concept.
*/
package gocelery
import (
"encoding/json"
"fmt"
"github.com/gomodule/redigo/redis"
)
// RedisCeleryBackend is celery backend for redis
type RedisCeleryBackend struct {
*redis.Pool
}
// NewRedisBackend creates new RedisCeleryBackend with given redis pool.
// RedisCeleryBackend can be initialized manually as well.
func NewRedisBackend(conn *redis.Pool) *RedisCeleryBackend {
return &RedisCeleryBackend{
Pool: conn,
}
}
// NewRedisCeleryBackend creates new RedisCeleryBackend
//
// Deprecated: NewRedisCeleryBackend exists for historical compatibility
// and should not be used. Pool should be initialized outside of gocelery package.
func NewRedisCeleryBackend(uri string) *RedisCeleryBackend {
return &RedisCeleryBackend{
Pool: NewRedisPool(uri),
}
}
// GetResult queries redis backend to get asynchronous result
func (cb *RedisCeleryBackend) GetResult(taskID string) (*ResultMessage, error) {
conn := cb.Get()
defer conn.Close()
val, err := conn.Do("GET", fmt.Sprintf("celery-task-meta-%s", taskID))
if err != nil {
return nil, err
}
if val == nil {
return nil, fmt.Errorf("result not available")
}
var resultMessage ResultMessage
err = json.Unmarshal(val.([]byte), &resultMessage)
if err != nil {
return nil, err
}
return &resultMessage, nil
}
// SetResult pushes result back into redis backend
func (cb *RedisCeleryBackend) SetResult(taskID string, result *ResultMessage) error {
result.ID = taskID
resBytes, err := json.Marshal(result)
if err != nil {
return err
}
conn := cb.Get()
defer conn.Close()
_, err = conn.Do("SETEX", fmt.Sprintf("celery-task-meta-%s", taskID), 86400, resBytes)
return err
}