Turning Off Echo’d Messages

By default a NATS connection will echo messages if the connection also has interest in the published subject. This means that if a publisher on a connection sends a message to a subject any subscribers on that same connection will receive the message. Clients can opt to turn off this behavior, such that regardless of interest, the message will not be delivered to subscribers on the same connection.

The NoEcho option can be useful in BUS patterns where all applications subscribe and publish to the same subject. Usually a publish represents a state change that the application already knows about, so in the case where the application publishes an update it does not need to process the update itself.

Turning Off Echo’d Messages - 图1

Keep in mind that each connection will have to turn off echo, and that it is per connection, not per application. Also, turning echo on and off can result in a major change to your applications communications protocol since messages will flow or stop flowing based on this setting and the subscribing code won’t have any indication as to why.

Go

  1. // Turn off echo
  2. nc, err := nats.Connect("demo.nats.io", nats.Name("API NoEcho Example"), nats.NoEcho())
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. defer nc.Close()
  7. // Do something with the connection

Java

  1. Options options = new Options.Builder().
  2. server("nats://demo.nats.io:4222").
  3. noEcho(). // Turn off echo
  4. build();
  5. Connection nc = Nats.connect(options);
  6. // Do something with the connection
  7. nc.close();

JavaScript

  1. const nc = await connect({
  2. servers: ["demo.nats.io"],
  3. noEcho: true,
  4. });
  5. const sub = nc.subscribe(subj, { callback: (_err, _msg) => {} });
  6. nc.publish(subj);
  7. await sub.drain();
  8. // we won't get our own messages
  9. t.is(sub.getProcessed(), 0);

Python

  1. ncA = NATS()
  2. ncB = NATS()
  3. await ncA.connect(no_echo=True)
  4. await ncB.connect()
  5. async def handler(msg):
  6. # Messages sent by `ncA' will not be received.
  7. print("[Received] ", msg)
  8. await ncA.subscribe("greetings", cb=handler)
  9. await ncA.flush()
  10. await ncA.publish("greetings", b'Hello World!')
  11. await ncB.publish("greetings", b'Hello World!')
  12. # Do something with the connection
  13. await asyncio.sleep(1)
  14. await ncA.drain()
  15. await ncB.drain()

Ruby

  1. NATS.start("nats://demo.nats.io:4222", no_echo: true) do |nc|
  2. # ...
  3. end

C

  1. natsConnection *conn = NULL;
  2. natsOptions *opts = NULL;
  3. natsStatus s = NATS_OK;
  4. s = natsOptions_Create(&opts);
  5. if (s == NATS_OK)
  6. s = natsOptions_SetNoEcho(opts, true);
  7. if (s == NATS_OK)
  8. s = natsConnection_Connect(&conn, opts);
  9. (...)
  10. // Destroy objects that were created
  11. natsConnection_Destroy(conn);
  12. natsOptions_Destroy(opts);

{% endtabs %}