forked from pebbe/zmq3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clonecli2.go
70 lines (61 loc) · 1.71 KB
/
clonecli2.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
//
// Clone client Model Two
//
// In the original C example, the client misses updates between snapshot
// and further updates. Sometimes, it even misses the END message of
// the snapshot, so it waits for it forever.
// This Go implementation has some modifications to improve this, but it
// is still not fully reliable.
package main
import (
zmq "github.com/pebbe/zmq3"
"github.com/pebbe/zmq3/examples/kvsimple"
"fmt"
"time"
)
func main() {
snapshot, _ := zmq.NewSocket(zmq.DEALER)
snapshot.Connect("tcp://localhost:5556")
subscriber, _ := zmq.NewSocket(zmq.SUB)
subscriber.SetRcvhwm(100000) // or messages between snapshot and next are lost
subscriber.SetSubscribe("")
subscriber.Connect("tcp://localhost:5557")
time.Sleep(time.Second) // or messages between snapshot and next are lost
kvmap := make(map[string]*kvsimple.Kvmsg)
// Get state snapshot
sequence := int64(0)
snapshot.SendMessage("ICANHAZ?")
for {
kvmsg, err := kvsimple.RecvKvmsg(snapshot)
if err != nil {
fmt.Println(err)
break // Interrupted
}
if key, _ := kvmsg.GetKey(); key == "KTHXBAI" {
sequence, _ = kvmsg.GetSequence()
fmt.Printf("Received snapshot=%d\n", sequence)
break // Done
}
kvmsg.Store(kvmap)
}
snapshot.Close()
first := true
// Now apply pending updates, discard out-of-sequence messages
for {
kvmsg, err := kvsimple.RecvKvmsg(subscriber)
if err != nil {
fmt.Println(err)
break // Interrupted
}
if seq, _ := kvmsg.GetSequence(); seq > sequence {
sequence, _ = kvmsg.GetSequence()
kvmsg.Store(kvmap)
if first {
// Show what the first regular update is after the snapshot,
// to see if we missed updates.
first = false
fmt.Println("Next:", sequence)
}
}
}
}