Skip to content

Commit 5da3044

Browse files
committed
docs: update example
Signed-off-by: Bo-Yi Wu <[email protected]>
1 parent 3a2c115 commit 5da3044

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

README.md

+88
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,94 @@ redis-server
1515

1616
![screen](/images/screen.png)
1717

18+
start the redis cluster, see the [config](./conf/redis.conf)
19+
20+
```sh
21+
# server 01
22+
mkdir server01 && cd server 01 && redis-server redis.conf --port 6379
23+
# server 02
24+
mkdir server02 && cd server 02 && redis-server redis.conf --port 6380
25+
```
26+
27+
## Example
28+
29+
For single server
30+
31+
```go
32+
package main
33+
34+
import (
35+
"context"
36+
"encoding/json"
37+
"fmt"
38+
"log"
39+
"time"
40+
41+
"github.com/golang-queue/queue"
42+
"github.com/golang-queue/redisdb"
43+
)
44+
45+
type job struct {
46+
Message string
47+
}
48+
49+
func (j *job) Bytes() []byte {
50+
b, err := json.Marshal(j)
51+
if err != nil {
52+
panic(err)
53+
}
54+
return b
55+
}
56+
57+
func main() {
58+
taskN := 100
59+
rets := make(chan string, taskN)
60+
61+
// define the worker
62+
w := redisdb.NewWorker(
63+
redisdb.WithAddr("127.0.0.1:6379"),
64+
redisdb.WithChannel("foobar"),
65+
redisdb.WithRunFunc(func(ctx context.Context, m queue.QueuedMessage) error {
66+
v, ok := m.(*job)
67+
if !ok {
68+
if err := json.Unmarshal(m.Bytes(), &v); err != nil {
69+
return err
70+
}
71+
}
72+
73+
rets <- v.Message
74+
return nil
75+
}),
76+
)
77+
78+
// define the queue
79+
q := queue.NewPool(
80+
5,
81+
queue.WithWorker(w),
82+
)
83+
84+
// assign tasks in queue
85+
for i := 0; i < taskN; i++ {
86+
go func(i int) {
87+
if err := q.Queue(&job{
88+
Message: fmt.Sprintf("handle the job: %d", i+1),
89+
}); err != nil {
90+
log.Fatal(err)
91+
}
92+
}(i)
93+
}
94+
95+
// wait until all tasks done
96+
for i := 0; i < taskN; i++ {
97+
fmt.Println("message:", <-rets)
98+
time.Sleep(50 * time.Millisecond)
99+
}
100+
101+
// shutdown the service and notify all the worker
102+
q.Release()
103+
}
104+
```
105+
18106
## Testing
19107

20108
```sh

0 commit comments

Comments
 (0)