-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpub_sub.go
62 lines (55 loc) · 1.66 KB
/
pub_sub.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
package rmq
import (
"context"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
"strconv"
"strings"
)
type PubSubMQ struct {
client *redis.Client // Redis客户端
}
func NewPubSubMQ(client *redis.Client) *PubSubMQ {
return &PubSubMQ{client: client}
}
func (q *PubSubMQ) SendMsg(ctx context.Context, msg *Msg) error {
return q.client.Publish(ctx, q.partitionTopic(msg.Topic, msg.Partition), msg.Body).Err()
}
// Consume 返回值代表消费过程中遇到的无法处理的错误
func (q *PubSubMQ) Consume(ctx context.Context, topic string, partition int, h Handler) error {
// 订阅频道
channel := q.client.Subscribe(ctx, q.partitionTopic(topic, partition)).Channel()
for msg := range channel {
// 处理消息
h(&Msg{
Topic: topic,
Body: []byte(msg.Payload),
Partition: partition,
})
}
return errors.New("channel closed")
}
// ConsumeMultiPartitions 返回值代表消费过程中遇到的无法处理的错误
func (q *PubSubMQ) ConsumeMultiPartitions(ctx context.Context, topic string, partitions []int, h Handler) error {
// 订阅频道
channels := make([]string, len(partitions))
for i, partition := range partitions {
channels[i] = q.partitionTopic(topic, partition)
}
channel := q.client.Subscribe(ctx, channels...).Channel()
for msg := range channel {
// 处理消息
_, partitionString, _ := strings.Cut(msg.Channel, ":")
partition, _ := strconv.Atoi(partitionString)
h(&Msg{
Topic: topic,
Body: []byte(msg.Payload),
Partition: partition,
})
}
return errors.New("channels closed")
}
func (q *PubSubMQ) partitionTopic(topic string, partition int) string {
return fmt.Sprintf("%s:%d", topic, partition)
}