Powered By GitBook
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.
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
Java
JavaScript
Python
Ruby
TypeScript
C
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
8
// Do something with the connection
Copied!
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
7
// Do something with the connection
8
9
nc.close();
Copied!
1
let nc = NATS.connect({
2
url: "nats://demo.nats.io:4222",
3
noEcho: true
4
});
Copied!
1
ncA = NATS()
2
ncB = NATS()
3
4
await ncA.connect(no_echo=True)
5
await ncB.connect()
6
7
async def handler(msg):
8
# Messages sent by `ncA' will not be received.
9
print("[Received] ", msg)
10
11
await ncA.subscribe("greetings", cb=handler)
12
await ncA.flush()
13
await ncA.publish("greetings", b'Hello World!')
14
await ncB.publish("greetings", b'Hello World!')
15
16
# Do something with the connection
17
18
await asyncio.sleep(1)
19
await ncA.drain()
20
await ncB.drain()
Copied!
1
NATS.start("nats://demo.nats.io:4222", no_echo: true) do |nc|
2
# ...
3
end
Copied!
1
let nc = await connect({
2
url: "nats://demo.nats.io:4222", noEcho: true});
Copied!
1
natsConnection *conn = NULL;
2
natsOptions *opts = NULL;
3
natsStatus s = NATS_OK;
4
5
s = natsOptions_Create(&opts);
6
if (s == NATS_OK)
7
s = natsOptions_SetNoEcho(opts, true);
8
if (s == NATS_OK)
9
s = natsConnection_Connect(&conn, opts);
10
11
(...)
12
13
// Destroy objects that were created
14
natsConnection_Destroy(conn);
15
natsOptions_Destroy(opts);
Copied!
Last modified 10mo ago
Export as PDF
Copy link