-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
143 lines (132 loc) · 3.39 KB
/
stream.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package gfrds
import (
"context"
"encoding/json"
"fmt"
"github.com/brunowang/gframe/gflog"
"github.com/brunowang/gframe/gfserial"
"github.com/fatih/structs"
"github.com/go-redis/redis/v7"
"go.uber.org/zap"
"reflect"
"time"
)
type RedisStream struct {
cli *redis.Client
}
func NewRedisStream(cli *redis.Client) *RedisStream {
return &RedisStream{cli: cli}
}
type consumeFunc func(ctx context.Context, msg redis.XMessage) error
func (r *RedisStream) Consume(ctx context.Context, stream, group string, fn consumeFunc, opts ...ConsumeOption) error {
var lastErr error
defer func() {
if err := recover(); err != nil {
gflog.Error(ctx, "mq consume recovered", zap.String("stream", stream), zap.Any("error", err))
lastErr = fmt.Errorf("%+v", err)
return
}
}()
options := consumeOptions{
ReadCount: 1,
ReconnectSec: 5,
}
for _, opt := range opts {
opt(&options)
}
xargs := &redis.XReadGroupArgs{
Group: group,
Consumer: options.ConsumerName,
Streams: []string{stream, ">"},
Count: options.ReadCount,
}
for {
res, err := r.cli.XReadGroup(xargs).Result()
if err == redis.ErrClosed {
gflog.Error(ctx, "mq conn closed", zap.String("stream", stream), zap.Error(err))
break
} else if err != nil {
gflog.Error(ctx, "mq consume failed", zap.String("stream", stream), zap.Error(err))
time.Sleep(time.Duration(options.ReconnectSec) * time.Second)
continue
}
for _, s := range res {
for _, msg := range s.Messages {
if err := fn(ctx, msg); err != nil {
gflog.Error(ctx, "fn invoke failed", zap.String("stream", stream), zap.Error(err))
r.cli.XAck(stream, group, msg.ID)
continue
}
r.cli.XAck(stream, group, msg.ID)
}
}
}
return lastErr
}
func (r *RedisStream) Produce(ctx context.Context, stream string, msg interface{}, opts ...ProduceOption) error {
if msg == nil {
return fmt.Errorf("mq produce got nil msg")
}
options := produceOptions{
DefaultKey: "message",
}
for _, opt := range opts {
opt(&options)
}
vals := make(map[string]interface{})
if m, ok := msg.(map[string]interface{}); ok {
vals = m
} else if m, ok := msg.(*map[string]interface{}); ok {
vals = *m
} else if m, ok := msg.(gfserial.Serializable); ok {
bs, err := m.Serialize()
if err != nil {
return err
}
if err := json.Unmarshal(bs, &vals); err != nil {
vals = map[string]interface{}{options.DefaultKey: bs}
}
} else if m, ok := msg.(gfserial.Mapper); ok {
m, err := m.ToMap()
if err != nil {
return err
}
vals = m
} else {
v := reflect.ValueOf(msg)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() == reflect.Invalid {
return fmt.Errorf("mq produce got invalid msg %+v, typ %T", msg, msg)
}
switch v.Kind() {
case reflect.Struct:
vals = structs.Map(v.Interface())
case reflect.Map:
keys := v.MapKeys()
for _, k := range keys {
key := k.String()
if k.Kind() != reflect.String {
key = fmt.Sprintf("%v", k.Interface())
}
val := v.MapIndex(k)
vals[key] = val.Interface()
}
default:
vals = map[string]interface{}{options.DefaultKey: v.Interface()}
}
}
if len(vals) == 0 {
return fmt.Errorf("mq produce got empty msg %+v, typ %T", msg, msg)
}
if err := r.cli.XAdd(&redis.XAddArgs{
Stream: stream,
ID: "*",
Values: vals,
}).Err(); err != nil {
gflog.Error(ctx, "mq produce failed", zap.String("stream", stream), zap.Error(err))
return err
}
return nil
}