Last active
April 6, 2020 04:05
-
-
Save pot-code/5317d8b24d037aa7d37261650e59a61e to your computer and use it in GitHub Desktop.
[zmq] zeromq snippets #MQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
if len(os.Args) < 2 || os.Args[1] != "client" { | |
for i := 0; i < 4; i++ { | |
go worker() | |
} | |
broker() | |
} else { | |
client() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func client() { | |
ctx, _ := zmq.NewContext() | |
soc, _ := ctx.NewSocket(zmq.REQ) | |
retries := 3 | |
poller := zmq.NewPoller() | |
soc.Connect("tcp://localhost:8081") | |
for retries > 0 { | |
id := poller.Add(soc, zmq.POLLIN) | |
// send | |
events, err := poller.Poll(3 * time.Second) | |
if err != nil { | |
log.Fatal(err) | |
} | |
if len(events) == 0 { | |
retries-- | |
if retries == 0 { | |
log.Fatal("server seems to be down, bail out") | |
} else { | |
log.Printf("no response from server, retrying...") | |
soc.Close() | |
poller.Remove(id) | |
soc, _ = ctx.NewSocket(zmq.REQ) | |
soc.Connect("tcp://localhost:8081") | |
} | |
} else { | |
// receive | |
poller.Remove(id) | |
retries = 3 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func dealer() { | |
ctx, _ := zmq.NewContext() | |
frontend, _ := ctx.NewSocket(zmq.ROUTER) | |
backend, _ := ctx.NewSocket(zmq.DEALER) | |
poller := zmq.NewPoller() | |
frontend.Bind("tcp://*:8081") | |
backend.Bind("tcp://*:8080") | |
poller.Add(frontend, zmq.POLLIN) | |
poller.Add(backend, zmq.POLLIN) | |
for { | |
sockets, _ := poller.Poll(-1) | |
for _, soc := range sockets { | |
switch soc.Socket { | |
case frontend: | |
case backend: | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment