-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpartition_ack_list.go
54 lines (48 loc) · 1.31 KB
/
partition_ack_list.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
package rmq
import (
"context"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
"time"
)
type PartitionACKListMQ struct {
client *redis.Client // Redis客户端
}
func NewPartitionACKListMQ(client *redis.Client) *PartitionACKListMQ {
return &PartitionACKListMQ{client: client}
}
func (q *PartitionACKListMQ) SendMsg(ctx context.Context, msg *Msg) error {
return q.client.LPush(ctx, q.partitionTopic(msg.Topic, msg.Partition), msg.Body).Err()
}
// Consume 返回值代表消费过程中遇到的无法处理的错误
func (q *PartitionACKListMQ) Consume(ctx context.Context, topic string, partition int, h Handler) error {
for {
// 获取消息
body, err := q.client.LIndex(ctx, q.partitionTopic(topic, partition), -1).Bytes()
if err != nil && !errors.Is(err, redis.Nil) {
return err
}
// 没有消息了,休眠一会
if errors.Is(err, redis.Nil) {
time.Sleep(time.Second)
continue
}
// 处理消息
err = h(&Msg{
Topic: topic,
Body: body,
Partition: partition,
})
if err != nil {
continue
}
// 如果处理成功,删除消息
if err := q.client.RPop(ctx, q.partitionTopic(topic, partition)).Err(); err != nil {
return err
}
}
}
func (q *PartitionACKListMQ) partitionTopic(topic string, partition int) string {
return fmt.Sprintf("%s:%d", topic, partition)
}