-
Notifications
You must be signed in to change notification settings - Fork 2
/
message.go
55 lines (45 loc) · 1.24 KB
/
message.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
package bus
import (
"encoding/json"
)
// Message 消息结构体
type Message struct {
// BizUID 消息唯一标识
// 无特殊业务含义, 通常用于幂等性处理防止重复消费
BizUID string `json:"b,omitempty"`
// Payload 原始消息内容
Payload []byte `json:"p,omitempty"`
// Retried 记录消息重试次数
Retried int `json:"r,omitempty"`
// RouteKey 路由键
RouteKey string `json:"k,omitempty"`
}
// Scan 将消息内容赋值给目标参数
func (m *Message) Scan(dest interface{}) { decode(m.Payload, dest) }
// MessageAutoId 实例化消息
func MessageAutoId(payload interface{}, routeKey string) *Message {
return MessageWithId(generateSeqId(), payload, routeKey)
}
// MessageWithId 实例化消息
func MessageWithId(id string, payload interface{}, routeKey string) *Message {
return &Message{
BizUID: id,
Payload: encode(payload),
RouteKey: routeKey,
}
}
// encode 数据编码
func encode(data interface{}) []byte {
bts, err := json.Marshal(data)
if err != nil {
throw("easy-bus: encode error, %v", err)
}
return bts
}
// decode 数据解码
func decode(bts []byte, dest interface{}) {
err := json.Unmarshal(bts, dest)
if err != nil {
throw("easy-bus: decode [%s] error, %v", string(bts), err)
}
}