forked from mperham/resque-client.go
/
resque.go
128 lines (105 loc) · 2.36 KB
/
resque.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package resque
import (
"fmt"
"github.com/garyburd/redigo/redis"
"encoding/json"
"log"
// "strings"
// "strconv"
"time"
)
type ClientSpec struct {
RedisLocation string
RedisDatabase int
Queue string
WorkerCount int
}
type Client struct {
spec *ClientSpec
conn *redis.Conn
}
const (
DefaultLocation = "localhost:6379"
DefaultDatabase = 0
DefaultQueue = "test_queue"
DefaultWorkerCount = 4
)
func DefaultSpec() *ClientSpec {
return &ClientSpec{
DefaultLocation,
DefaultDatabase,
DefaultQueue,
DefaultWorkerCount,
}
}
type Job struct {
Class string `json:"class"`
Args []json.RawMessage `json:"args"`
}
func (c Client) Next() *Job {
log.Println("Fetching job from", c.spec.Queue)
multiBulk, _ := redis.MultiBulk((*c.conn).Do("BLPOP", c.spec.Queue, 0))
for len(multiBulk) > 0 {
var jobData []byte
multiBulk, _ = redis.Scan(multiBulk, &jobData)
// The first element returned is the queue name.
if string(jobData) == c.spec.Queue {
continue
}
job := new(Job)
log.Println("job", string(jobData))
json.Unmarshal(jobData, &job)
return job
}
return nil
}
func NewClient(cspec *ClientSpec) Client{
if cspec == nil {
cspec = DefaultSpec()
}
cspec.Queue = fmt.Sprintf("resque:queue:%s", cspec.Queue)
client, e := redis.Dial("tcp", cspec.RedisLocation)
if e != nil {
log.Panicln ("failed to create the client", e);
}
// Select their database.
client.Send("SELECT", cspec.RedisDatabase)
client.Flush()
ok, receiveE := client.Receive()
if ok != "OK" || receiveE != nil {
log.Panicln("Unable to switch database.", receiveE)
}
return Client{
cspec,
&client,
}
}
func (client *Client) Process() {
job := client.Next()
if job == nil {
return
}
if job.Class == "" {
log.Panicln("No class found in payload", job)
}
function := workerFunctions[job.Class]
if function == nil {
log.Panicln("No function registered for job", job.Class)
}
function(job.Args)
}
var workerFunctions = make(map[string] func([]json.RawMessage))
func Register(name string, processor func([]json.RawMessage)) {
workerFunctions[name] = processor
}
func myProcessor(args []json.RawMessage) {
log.Println(args)
}
func main() {
Register("Job", myProcessor)
client := NewClient(nil)
for {
client.Process()
time.Sleep(1000000000)
}
}