Skip to content

Instantly share code, notes, and snippets.

@nickcarenza
Created October 1, 2015 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickcarenza/9244722c8a9d0faa188e to your computer and use it in GitHub Desktop.
Save nickcarenza/9244722c8a9d0faa188e to your computer and use it in GitHub Desktop.
Request/reply with multiple subscribers
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
@derekcollison
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment