Created
October 1, 2015 17:17
-
-
Save nickcarenza/9244722c8a9d0faa188e to your computer and use it in GitHub Desktop.
Request/reply with multiple subscribers
This file contains hidden or 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
package main | |
import( | |
"fmt" | |
"log" | |
"github.com/nats-io/nats" | |
"time" | |
) | |
func main(){ | |
nc, err := nats.Connect("nats://192.168.99.100:32772") | |
if err != nil { | |
log.Fatal(err) | |
} | |
nc.QueueSubscribe("msg","one",func(msg *nats.Msg){ | |
fmt.Printf("one heard %s\n", string(msg.Data)) | |
nc.Publish(msg.Reply, []byte("one is here")) | |
}) | |
nc.QueueSubscribe("msg","two",func(msg *nats.Msg){ | |
fmt.Printf("two heard %s\n", string(msg.Data)) | |
nc.Publish(msg.Reply, []byte("two is here")) | |
}) | |
inbox := nats.NewInbox() | |
_, err = nc.Subscribe(inbox, func(msg *nats.Msg){ | |
fmt.Printf("requestor received %s\n", string(msg.Data)) | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
err = nc.PublishRequest("msg", inbox, []byte("help")) | |
if err != nil { | |
log.Fatal(err) | |
} | |
time.Sleep(1 * time.Second) | |
} | |
// Output: | |
// one heard help | |
// two heard help | |
// requestor received one is here | |
// requestor received two is here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use a Request with a timeout from the requestor side and retry on a timeout. That way it does not matter if the subscribers are coming or going or if they fail, just matter if the requestor gets the answer they want. Most situations are non-transactional so this patter works well.