-
Notifications
You must be signed in to change notification settings - Fork 5
/
write_back.go
78 lines (74 loc) · 2.14 KB
/
write_back.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
package main
import (
"encoding/json"
"io"
"log"
"net"
"strconv"
"strings"
)
func sendMessage(wf io.Writer, conn *net.UDPConn, cacheName string, key string, m map[string]interface{}) error {
v, err := json.Marshal(m)
if err != nil {
return err
}
s := strings.Replace(cacheName+"_"+key, "|", "_", -1) + "|" + string(v)
udpSend(conn, s)
return writeLine(wf, "+OK")
}
func writeBack(handlers map[string]handler, config map[string]interface{}, ctx *context) map[string]handler {
if config["write_back_target"] == nil {
return handlers
}
ra, err := net.ResolveUDPAddr("udp", config["write_back_target"].(string))
if err != nil {
panic(err)
}
conn, err := net.DialUDP("udp", nil, ra)
if err != nil {
panic(err)
}
if config["write_back_setTimeout"] != nil {
cacheName := "CACHE_" + strings.ToUpper(ctx.set)
m := make(map[string]interface{})
m["cache_name"] = cacheName
m["method"] = "setTimeout"
a := make([]interface{}, 2)
m["args"] = a
log.Printf("%s: Using write back for setTimeout to %s", ctx.set, config["write_back_target"])
f := func(wf io.Writer, ctx *context, args [][]byte) error {
key := string(args[0])
ttl, err := strconv.Atoi(string(args[1]))
if err != nil {
return err
}
a[0] = key
a[1] = ttl
return sendMessage(wf, conn, cacheName, key, m)
}
handlers["EXPIRE"] = handler{handlers["EXPIRE"].argsCount, handlers["EXPIRE"].argsLogCount, f, true}
}
if config["write_back_hIncrBy"] != nil {
cacheName := "CACHE_" + strings.ToUpper(ctx.set)
m := make(map[string]interface{})
m["cache_name"] = cacheName
m["method"] = "hIncrBy"
a := make([]interface{}, 3)
m["args"] = a
log.Printf("%s: Using write back for hIncrBy to %s", ctx.set, config["write_back_target"])
f := func(wf io.Writer, ctx *context, args [][]byte) error {
key := string(args[0])
field := string(args[1])
incr, err := strconv.Atoi(string(args[2]))
if err != nil {
return err
}
a[0] = key
a[1] = field
a[2] = incr
return sendMessage(wf, conn, cacheName, key, m)
}
handlers["HINCRBY"] = handler{handlers["HINCRBY"].argsCount, handlers["HINCRBY"].argsLogCount, f, true}
}
return handlers
}