Connection Name

Connections can be assigned a name which will appear in some of the server monitoring data. This name is not required, but is highly recommended as a friendly connection name will help in monitoring, error reporting, debugging, and testing.

Go

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

Java

  1. Options options = new Options.Builder().
  2. server("nats://demo.nats.io:4222").
  3. connectionName("API Name Option Example"). // Set Name
  4. build();
  5. Connection nc = Nats.connect(options);
  6. // Do something with the connection
  7. nc.close();

JavaScript

  1. let nc = NATS.connect({
  2. url: "nats://demo.nats.io:4222",
  3. name: "API Name Option Example"
  4. });
  5. nc.on('connect', (c) => {
  6. // Do something with the connection
  7. doSomething();
  8. // When done close it
  9. nc.close();
  10. });
  11. nc.on('error', (err) => {
  12. failed(err);
  13. });

Python

  1. nc = NATS()
  2. await nc.connect(
  3. servers=["nats://demo.nats.io:4222"],
  4. name="API Name Option Example")
  5. # Do something with the connection
  6. await nc.close()

Ruby

  1. require 'nats/client'
  2. NATS.start(servers: ["nats://demo.nats.io:4222"], name: "API Name Option Example") do |nc|
  3. # Do something with the connection
  4. # Close the connection
  5. nc.close
  6. end

TypeScript

  1. // will throw an exception if connection fails
  2. let nc = await connect({
  3. url:"nats://demo.nats.io:4222",
  4. name: "API Name Option Example"
  5. })
  6. // Do something with the connection
  7. // Close the connection
  8. nc.close();

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_SetName(opts, "API Name Option Example");
  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);