-
Notifications
You must be signed in to change notification settings - Fork 4
/
service.go
88 lines (75 loc) · 1.79 KB
/
service.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
package main
import (
"hash/crc32"
"sync"
"github.com/clubpay/ronykit/example/ex-03-cluster/dto"
"github.com/clubpay/ronykit/kit"
"github.com/clubpay/ronykit/kit/desc"
"github.com/clubpay/ronykit/kit/utils"
"github.com/clubpay/ronykit/kit/utils/reflector"
"github.com/clubpay/ronykit/std/gateways/fasthttp"
)
var (
kvl sync.RWMutex
kv = map[string]string{}
r = reflector.New()
)
var serviceDesc desc.ServiceDescFunc = func() *desc.Service {
return desc.NewService("SampleService").
SetEncoding(kit.JSON).
AddContract(
desc.NewContract().
SetCoordinator(coordinator).
SetInput(&dto.SetKeyRequest{}).
SetOutput(&dto.SetKeyResponse{}).
AddSelector(fasthttp.POST("/set")).
SetHandler(SetKeyHandler),
desc.NewContract().
SetCoordinator(coordinator).
SetInput(&dto.GetKeyRequest{}).
SetOutput(&dto.Key{}).
AddSelector(fasthttp.GET("/get/:key")).
SetHandler(GetKeyHandler),
)
}
func coordinator(ctx *kit.LimitedContext) (string, error) {
members, err := ctx.ClusterMembers()
if err != nil {
return "", err
}
key, err := r.GetString(ctx.In().GetMsg(), "Key")
if err != nil {
return "", err
}
return members[crc32.ChecksumIEEE(utils.S2B(key))%uint32(len(members))], nil
}
func SetKeyHandler(ctx *kit.Context) {
//nolint:forcetypeassert
req := ctx.In().GetMsg().(*dto.SetKeyRequest)
kvl.Lock()
kv[req.Key] = req.Value
kvl.Unlock()
ctx.In().Reply().
SetHdr("ClusterID", ctx.ClusterID()).
SetMsg(
&dto.SetKeyResponse{
Success: true,
},
).Send()
return
}
func GetKeyHandler(ctx *kit.Context) {
//nolint:forcetypeassert
req := ctx.In().GetMsg().(*dto.GetKeyRequest)
kvl.Lock()
v := kv[req.Key]
kvl.Unlock()
ctx.In().Reply().
SetHdr("ClusterID", ctx.ClusterID()).
SetMsg(
&dto.Key{
Value: v,
},
).Send()
return
}