| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"time" |
| 6 |
|
| 7 |
"github.com/nats-io/nats.go" |
| 8 |
) |
| 9 |
|
| 10 |
func main() { |
| 11 |
nc, _ := nats.Connect(nats.DefaultURL) |
| 12 |
defer nc.Close() |
| 13 |
|
| 14 |
// NATS-DOC-START |
| 15 |
processCalculation := func(data []byte) []byte { |
| 16 |
return []byte("calculated result") |
| 17 |
} |
| 18 |
|
| 19 |
// Multiple responders - only first response is returned |
| 20 |
nc.Subscribe("calc.add", func(m *nats.Msg) { |
| 21 |
result := processCalculation(m.Data) |
| 22 |
m.Respond(append(result, []byte(" from A")...)) |
| 23 |
}) |
| 24 |
|
| 25 |
nc.Subscribe("calc.add", func(m *nats.Msg) { |
| 26 |
result := processCalculation(m.Data) |
| 27 |
m.Respond(append(result, []byte(" from B")...)) |
| 28 |
}) |
| 29 |
|
| 30 |
// Gets one response |
| 31 |
msg, _ := nc.Request("calc.add", []byte("data"), time.Second) |
| 32 |
fmt.Printf("Got response: %s\n", msg.Data) |
| 33 |
// NATS-DOC-END |
| 34 |
} |