-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
52 lines (41 loc) · 1.21 KB
/
main.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
package main
import (
"fmt"
"sync/atomic"
"github.com/ibllex/go-queue"
"github.com/ibllex/go-queue/memq"
)
const taskRoute = "task"
var sum = int32(0)
type AddUpTask struct {
Count int32
}
// Every task must have a Handle method and return an error
func (t *AddUpTask) Handle() error {
atomic.AddInt32(&sum, t.Count)
return nil
}
// OnQueue is optional, the task will be distributed to the default queue by default,
// if OnQueue is specified, it will be distributed to the specified queue
func (t *AddUpTask) OnQueue() string {
return taskRoute
}
func main() {
// You must use queue.TaskHandler() as the consumer's Handler,
// otherwise the tasks cannot be automatically distributed
q, err := memq.NewQueue(taskRoute, memq.WithSync(queue.TaskHandler()))
if err != nil {
panic(err)
}
queue.Add(q)
// This step is necessary, you must register the task before posting the task message,
// otherwise the task will not be processed correctly
queue.RegisterTask(&AddUpTask{})
// Dispatch the task
queue.DispatchTask(&AddUpTask{Count: 10})
// Output: now sum is 10
fmt.Printf("now sum is %d\n", sum)
queue.DispatchTask(&AddUpTask{Count: 20})
// Output: now sum is 30
fmt.Printf("now sum is %d\n", sum)
}