### Start Seed Server with Debugging Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/clustering/README.md Example of starting a seed server for a 3-node cluster with debug logging enabled using the -D flag. ```bash nats-server -p 4222 -cluster nats://localhost:4248 -D ``` -------------------------------- ### Java Ordered Consumer Example Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/consumers.md Illustrates setting up an ordered push consumer in Java. It includes message handling and subscription setup with ordered delivery enabled. ```java package io.nats.examples.jetstream; import io.nats.client.*; import io.nats.client.api.PublishAck; import io.nats.client.impl.NatsMessage; import io.nats.examples.ExampleArgs; import io.nats.examples.ExampleUtils; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.temporal.TemporalUnit; public class myExample { public static void main(String[] args) { final String subject = "foo"; try (Connection nc = Nats.connect(ExampleUtils.createExampleOptions("localhost"))) { // Create a JetStream context. This hangs off the original connection // allowing us to produce data to streams and consume data from // JetStream consumers. JetStream js = nc.jetStream(); // This example assumes there is a stream already created on subject "foo" and some messages already stored in that stream // create our message handler. MessageHandler handler = msg -> { System.out.println("\nMessage Received:"); if (msg.hasHeaders()) { System.out.println(" Headers:"); for (String key : msg.getHeaders().keySet()) { for (String value : msg.getHeaders().get(key)) { System.out.printf(" %s: %s\n", key, value); } } } System.out.printf(" Subject: %s Data: %s\n", msg.getSubject(), new String(msg.getData(), StandardCharsets.UTF_8)); System.out.println(" " + msg.metaData()); }; Dispatcher dispatcher = nc.createDispatcher(); PushSubscribeOptions pso = PushSubscribeOptions.builder().ordered(true).build(); JetStreamSubscription sub = js.subscribe(subject, dispatcher, handler, false, pso); Thread.sleep(100); sub.drain(Duration.ofMillis(100)); nc.drain(Duration.ofMillis(100)); } catch(Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Connect to NATS Server Source: https://github.com/nats-io/nats.docs/blob/master/_examples/connect_url.html Examples show how to establish a connection to a NATS server using the provided URL. It covers different client libraries and includes basic connection setup and closing. ```Go // If connecting to the default port, the URL can be simplified // to just the hostname/IP. // That is, the connect below is equivalent to: // nats.Connect("nats://demo.nats.io:4222") nc, err := nats.Connect("demo.nats.io") if err != nil { log.Fatal(err) } defer nc.Close() // Do something with the connection ``` ```Java Connection nc = Nats.connect("nats://demo.nats.io:4222"); // Do something with the connection nc.close(); ``` ```JavaScript let nc = NATS.connect("nats://demo.nats.io:4222"); nc.on('connect', (c) => { // Do something with the connection doSomething(); // When done close it nc.close() }); nc.on('error', (err) => { failed(err); }); ``` ```Python nc = NATS() await nc.connect(servers=["nats://demo.nats.io:4222"]) # Do something with the connection await nc.close() ``` ```Ruby require 'nats/client' NATS.start(servers: ["nats://demo.nats.io:4222"]) do |nc| # Do something with the connection # Close the connection nc.close end ``` ```TypeScript // will throw an exception if connection fails let nc = await connect("nats://demo.nats.io:4222"); // Do something with the connection // Close the connection nc.close(); ``` -------------------------------- ### C Example: NATS JetStream Consumer Setup Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/consumers.md This C code demonstrates the setup for NATS JetStream consumers, including stream creation, pull or asynchronous subscription, and pending limits. It handles stream existence checks and configuration. ```c printf("Async error: %u - %s\n", err, natsStatus_GetText(err)); natsSubscription_GetDropped(sub, (int64_t*) &dropped); } int main(int argc, char **argv) { natsConnection *conn = NULL; natsStatistics *stats = NULL; natsOptions *opts = NULL; natsSubscription *sub = NULL; natsMsg *msg = NULL; jsCtx *js = NULL; jsErrCode jerr = 0; jsOptions jsOpts; jsSubOptions so; natsStatus s; bool delStream = false; opts = parseArgs(argc, argv, usage); printf("Created %s subscription on '%s'.\n", (pull ? "pull" : (async ? "asynchronous" : "synchronous")), subj); s = natsOptions_SetErrorHandler(opts, asyncCb, NULL); if (s == NATS_OK) s = natsConnection_Connect(&conn, opts); if (s == NATS_OK) s = jsOptions_Init(&jsOpts); if (s == NATS_OK) s = jsSubOptions_Init(&so); if (s == NATS_OK) { so.Stream = stream; so.Consumer = durable; if (flowctrl) { so.Config.FlowControl = true; so.Config.Heartbeat = (int64_t)1E9; } } if (s == NATS_OK) s = natsConnection_JetStream(&js, conn, &jsOpts); if (s == NATS_OK) { jsStreamInfo *si = NULL; // First check if the stream already exists. s = js_GetStreamInfo(&si, js, stream, NULL, &jerr); if (s == NATS_NOT_FOUND) { jsStreamConfig cfg; // Since we are the one creating this stream, we can delete at the end. delStream = true; // Initialize the configuration structure. jsStreamConfig_Init(&cfg); cfg.Name = stream; // Set the subject cfg.Subjects = (const char*[1]){subj}; cfg.SubjectsLen = 1; // Make it a memory stream. cfg.Storage = js_MemoryStorage; // Add the stream, s = js_AddStream(&si, js, &cfg, NULL, &jerr); } if (s == NATS_OK) { printf("Stream %s has %" PRIu64 " messages (% ``` ```c PRIu64 " bytes)\n", si->Config->Name, si->State.Msgs, si->State.Bytes); // Need to destroy the returned stream object. jsStreamInfo_Destroy(si); } } if (s == NATS_OK) { if (pull) s = js_PullSubscribe(&sub, js, subj, durable, &jsOpts, &so, &jerr); else if (async) s = js_Subscribe(&sub, js, subj, onMsg, NULL, &jsOpts, &so, &jerr); else s = js_SubscribeSync(&sub, js, subj, &jsOpts, &so, &jerr); } if (s == NATS_OK) s = natsSubscription_SetPendingLimits(sub, -1, -1); if (s == NATS_OK) s = natsStatistics_Create(&stats); if ((s == NATS_OK) && pull) { natsMsgList list; int i; for (count = 0; (s == NATS_OK) && (count < total); ) { s = natsSubscription_Fetch(&list, sub, 1024, 5000, &jerr); if (s != NATS_OK) break; if (start == 0) start = nats_Now(); count += (int64_t) list.Count; for (i=0; (s == NATS_OK) && (iConfig->Name, si->State.Msgs, si->State.Bytes); jsStreamInfo_Destroy(si); } if (delStream) { printf("\nDeleting stream %s: ", stream); s = js_DeleteStream(js, stream, NULL, &jerr); if (s == NATS_OK) printf("OK!"); printf("\n"); } } else { printf("Error: %u - %s - jerr=%u\n", s, natsStatus_GetText(s), jerr); nats_PrintLastErrorStack(stderr); } // Destroy all our objects to avoid report of memory leak ``` -------------------------------- ### Install NATS Server Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/nats-tools/nsc/basics.md Use Go to install the NATS server binary. ```shell go get github.com/nats-io/nats-server ``` -------------------------------- ### NATS Server Gateway Startup Logs Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/gateways/gateway.md Example log output from a NATS server starting up with gateway configuration, showing listening addresses, gateway connections, and server readiness. ```log [85803] 2019/05/07 10:50:55.902474 [INF] Starting nats-server version 2.0.0 [85803] 2019/05/07 10:50:55.903669 [INF] Gateway name is A [85803] 2019/05/07 10:50:55.903684 [INF] Listening for gateways connections on localhost:7222 [85803] 2019/05/07 10:50:55.903696 [INF] Address for gateway "A" is localhost:7222 [85803] 2019/05/07 10:50:55.903909 [INF] Listening for client connections on 0.0.0.0:4222 [85803] 2019/05/07 10:50:55.903914 [INF] Server id is NBHUDBF3TVJSWCDPG2HSKI4I2SBSPDTNYEXEMOFAZUZYXVA2IYRUGPZU [85803] 2019/05/07 10:50:55.903917 [INF] Server is ready [85803] 2019/05/07 10:50:56.830669 [INF] 127.0.0.1:50892 - gid:2 - Processing inbound gateway connection [85803] 2019/05/07 10:50:56.830673 [INF] 127.0.0.1:50891 - gid:1 - Processing inbound gateway connection [85803] 2019/05/07 10:50:56.831079 [INF] 127.0.0.1:50892 - gid:2 - Inbound gateway connection from "C" (NBHWDFO3KHANNI6UCEUL27VNWL7NWD2MC4BI4L2C7VVLFBSMZ3CRD7HE) registered [85803] 2019/05/07 10:50:56.831211 [INF] 127.0.0.1:50891 - gid:1 - Inbound gateway connection from "B" (ND2UJB3GFUHXOQ2UUMZQGOCL4QVR2LRJODPZH7MIPGLWCQRARJBU27C3) registered [85803] 2019/05/07 10:50:56.906103 [INF] Connecting to explicit gateway "B" (localhost:7333) at 127.0.0.1:7333 [85803] 2019/05/07 10:50:56.906104 [INF] Connecting to explicit gateway "C" (localhost:7444) at 127.0.0.1:7444 [85803] 2019/05/07 10:50:56.906404 [INF] 127.0.0.1:7333 - gid:3 - Creating outbound gateway connection to "B" [85803] 2019/05/07 10:50:56.906444 [INF] 127.0.0.1:7444 - gid:4 - Creating outbound gateway connection to "C" [85803] 2019/05/07 10:50:56.906647 [INF] 127.0.0.1:7444 - gid:4 - Outbound gateway connection to "C" (NBHWDFO3KHANNI6UCEUL27VNWL7NWD2MC4BI4L2C7VVLFBSMZ3CRD7HE) registered [85803] 2019/05/07 10:50:56.906772 [INF] 127.0.0.1:7333 - gid:3 - Outbound gateway connection to "B" (ND2UJB3GFUHXOQ2UUMZQGOCL4QVR2LRJODPZH7MIPGLWCQRARJBU27C3) registered ``` -------------------------------- ### Run NATS Subscriber Example Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/running/nats_docker/ngs-docker-python.md Starts the NATS subscriber example script in the background. It connects to the NGS global server using TLS and listens for messages on the 'hello' subject. Ensure you have the 'NGS.creds' file mounted. ```shell python nats-sub.py --creds /creds/NGS.creds -s tls://connect.ngs.global:4222 hello & ``` -------------------------------- ### Install nk CLI tool Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/nats-tools/nk.md Uses the Go toolchain to download and install the latest version of the nk utility for managing NKeys. ```bash go install github.com/nats-io/nkeys/nk@latest ``` -------------------------------- ### Install and Start NATS Windows Service Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/running/windows_srv.md Commands to create and start the NATS server as a Windows service using `sc.exe`. Ensure to replace `[nats-server flags]` with your desired server configuration flags. ```shell sc.exe create nats-server binPath= "%NATS_PATH%\nats-server.exe [nats-server flags]" sc.exe start nats-server ``` -------------------------------- ### Install NATS Server Binary from Source Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/installation.md Uses the Go toolchain to fetch and install the latest development build of the NATS server from the main branch. ```shell go install github.com/nats-io/nats-server/v2@main ``` -------------------------------- ### Start NATS Server Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/leafnodes/README.md Command to start the NATS server using a specified configuration file. ```bash nats-server -c /tmp/server.conf ``` -------------------------------- ### Install NATS CLI and Server Tools Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/nats_admin/jwt.md Commands to install the NATS server, CLI, nkeys, and NSC tools using Go modules. ```shell export GO111MODULE=on go install github.com/nats-io/nats-server/v2@latest go install github.com/nats-io/natscli/nats@latest go install github.com/nats-io/nkeys/nk@latest go install github.com/nats-io/nsc/v2@latest ``` -------------------------------- ### Start NATS Server with Token Authentication Flag Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/securing_nats/auth_intro/tokens.md Demonstrates starting the NATS server process using the command-line interface with a specified authentication token. ```shell nats-server --auth s3cr3t ``` -------------------------------- ### JavaScript Ordered Consumer Example Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/consumers.md Shows how to set up an ordered consumer in JavaScript using `consumerOpts`. This consumer is not durable and will be auto-destroyed when the subscription ends. ```javascript import { connect, consumerOpts } from "../../src/mod.ts"; const nc = await connect(); const js = nc.jetstream(); // note the consumer is not durable - so after the // subscription ends, the server will auto destroy the // consumer const opts = consumerOpts(); opts.manualAck(); opts.maxMessages(2); opts.deliverTo("xxx"); const sub = await js.subscribe("a.>", opts); await (async () => { for await (const m of sub) { console.log(m.seq, m.subject); m.ack(); } })(); await nc.close(); ``` -------------------------------- ### Add Time-Based Consumer Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/jetstream/model_deep_dive.md Creates a pull-based consumer that starts delivering messages from a specific time in the past (2 minutes ago in this example). ```shell nats consumer add ORDERS 2MIN --pull --filter ORDERS.processed --ack none --replay instant --deliver 2m ``` -------------------------------- ### Start NATS Server with Configuration Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/securing_nats/jwt/mem_resolver.md This shell command demonstrates how to start the NATS server using a specified configuration file. It's a common command for initializing a NATS server instance with custom settings. ```shell nats-server -c server.conf ``` -------------------------------- ### Generate NATS Server Configuration and Start Server Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/nats_admin/jwt.md Generates a NATS server configuration file using `nsc` and starts the NATS server in the background. This configuration includes operator details and system account JWTs. Ensure the `nsc` tool is installed and configured. ```shell nsc generate config --nats-resolver > nats-res.cfg nats-server -c nats-res.cfg --addr localhost --port 4222 & ``` -------------------------------- ### NATS Server Configuration with Environment Variable Export Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/README.md Example of exporting an environment variable `TOKEN` before starting the NATS server, which will be used by the configuration file. ```shell export TOKEN="hello" nats-server -c /config/file ``` -------------------------------- ### Fetch Messages with Time-Based Consumer Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/jetstream/model_deep_dive.md Retrieves messages using a time-based consumer configured to start from 2 minutes ago. This example shows receiving a message published after that time. ```shell nats consumer next ORDERS 2MIN ``` -------------------------------- ### Go Ordered Consumer Example Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/consumers.md Demonstrates creating an ordered push consumer in Go. This consumer receives messages sequentially from the 'foo' stream. ```go func ExampleJetStream() { nc, err := nats.Connect("localhost") if err != nil { log.Fatal(err) } // Use the JetStream context to produce and consume messages // that have been persisted. js, err := nc.JetStream(nats.PublishAsyncMaxPending(256)) if err != nil { log.Fatal(err) } js.AddStream(&nats.StreamConfig{ Name: "FOO", Subjects: []string{"foo"}, }) js.Publish("foo", []byte("Hello JS!")) // ordered push consumer js.Subscribe("foo", func(msg *nats.Msg) { meta, _ := msg.Metadata() fmt.Printf("Stream Sequence : %v\n", meta.Sequence.Stream) fmt.Printf("Consumer Sequence: %v\n", meta.Sequence.Consumer) }, nats.OrderedConsumer()) } ``` -------------------------------- ### Go JetStream Consumer Examples Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/consumers.md Demonstrates various ways to create and use JetStream consumers in Go, including asynchronous and synchronous subscriptions, manual acknowledgments, and queue groups. ```go func ExampleJetStream() { nc, err := nats.Connect("localhost") if err != nil { log.Fatal(err) } // Use the JetStream context to produce and consume messages // that have been persisted. js, err := nc.JetStream(nats.PublishAsyncMaxPending(256)) if err != nil { log.Fatal(err) } js.AddStream(&nats.StreamConfig{ Name: "FOO", Subjects: []string{"foo"}, }) js.Publish("foo", []byte("Hello JS!")) // Publish messages asynchronously. for i := 0; i < 500; i++ { js.PublishAsync("foo", []byte("Hello JS Async!")) } select { case <-js.PublishAsyncComplete(): case <-time.After(5 * time.Second): fmt.Println("Did not resolve in time") } // Create async consumer on subject 'foo'. Async subscribers // ack a message once exiting the callback. js.Subscribe("foo", func(msg *nats.Msg) { meta, _ := msg.Metadata() fmt.Printf("Stream Sequence : %v\n", meta.Sequence.Stream) fmt.Printf("Consumer Sequence: %v\n", meta.Sequence.Consumer) }) // Async subscriber with manual acks. js.Subscribe("foo", func(msg *nats.Msg) { msg.Ack() }, nats.ManualAck()) // Async queue subscription where members load balance the // received messages together. // If no consumer name is specified, either with nats.Bind() // or nats.Durable() options, the queue name is used as the // durable name (that is, as if you were passing the // nats.Durable() option. // It is recommended to use nats.Bind() or nats.Durable() // and preferably create the JetStream consumer beforehand // (using js.AddConsumer) so that the JS consumer is not // deleted on an Unsubscribe() or Drain() when the member // that created the consumer goes away first. // Check Godoc for the QueueSubscribe() API for more details. js.QueueSubscribe("foo", "group", func(msg *nats.Msg) { msg.Ack() }, nats.ManualAck()) // Subscribe to consume messages synchronously. sub, _ := js.SubscribeSync("foo") msg, _ := sub.NextMsg(2 * time.Second) msg.Ack() // We can add a member to the group, with this member using // the synchronous version of the QueueSubscribe. sub, _ = js.QueueSubscribeSync("foo", "group") msg, _ = sub.NextMsg(2 * time.Second) msg.Ack() // ChanSubscribe msgCh := make(chan *nats.Msg, 8192) sub, _ = js.ChanSubscribe("foo", msgCh) select { case msg := <-msgCh: fmt.Println("[Received]", msg) case <-time.After(1 * time.Second): } } ``` -------------------------------- ### Second NATS Server Configuration with Bridging Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/securing_nats/jwt/jwt_nkey_auth.md An example configuration for a second NATS server that bridges to the first server. This setup is part of the strategy to transition between different authentication models. ```hcl port = 4223 cluster { port = 6223 routes [ nats://127.0.0.1:6222 ] } # debug = true # trace = true ``` -------------------------------- ### Go Pull-Based Consumer Example Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/consumers.md Demonstrates creating a pull-based consumer in Go, fetching messages in batches, and acknowledging them. The Fetch method returns as soon as any message is available. ```Go func ExampleJetStream() { nc, err := nats.Connect("localhost") if err != nil { log.Fatal(err) } // Use the JetStream context to produce and consume messages // that have been persisted. js, err := nc.JetStream(nats.PublishAsyncMaxPending(256)) if err != nil { log.Fatal(err) } js.AddStream(&nats.StreamConfig{ Name: "FOO", Subjects: []string{"foo"}, }) js.Publish("foo", []byte("Hello JS!")) // Publish messages asynchronously. for i := 0; i < 500; i++ { js.PublishAsync("foo", []byte("Hello JS Async!")) } select { case <-js.PublishAsyncComplete(): case <-time.After(5 * time.Second): fmt.Println("Did not resolve in time") } // Create Pull based consumer with maximum 128 inflight. sub, _ := js.PullSubscribe("foo", "wq", nats.PullMaxWaiting(128)) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() for { select { case <-ctx.Done(): return default: } // Fetch will return as soon as any message is available rather than wait until the full batch size is available, using a batch size of more than 1 allows for higher throughput when needed. msgs, _ := sub.Fetch(10, nats.Context(ctx)) for _, msg := range msgs { msg.Ack() } } } ``` -------------------------------- ### Obtain JetStream Context (Python) Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/context.md Provides an example of how to get the JetStream context in Python using the NATS client library. This context is essential for performing JetStream operations like publishing and subscribing. ```Python async def main(): nc = await nats.connect("localhost") # Create JetStream context. js = nc.jetstream() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### List Accounts and Users with NSC Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/securing_nats/jwt/jwt_nkey_auth.md These commands show how to list existing accounts and users managed by NSC. This is useful for verifying the setup and retrieving public keys for configuration. ```bash nsc list accounts ``` ```bash nsc list users -a A ``` -------------------------------- ### Starting Third NATS Server in Cluster Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/clustering/README.md This command initiates the third NATS server in the cluster, configuring its client port, cluster address, and routes to connect to the seed server. This completes the multi-server cluster setup. ```bash nats-server -p 6222 -cluster nats://localhost:6248 -routes nats://localhost:4248 -D ``` -------------------------------- ### JavaScript Pull Subscription Example Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/consumers.md Demonstrates setting up a pull subscription with explicit acknowledgments and batch fetching. It includes logic for handling redelivered messages and periodically pulling new messages. ```javascript import { AckPolicy, connect, nanos } from "../../src/mod.ts"; import { nuid } from "../../nats-base-client/nuid.ts"; const nc = await connect(); const stream = nuid.next(); const subj = nuid.next(); const durable = nuid.next(); const jsm = await nc.jetstreamManager(); await jsm.streams.add({ name: stream, subjects: [subj] }); const js = nc.jetstream(); await js.publish(subj); await js.publish(subj); await js.publish(subj); await js.publish(subj); const psub = await js.pullSubscribe(subj, { mack: true, // artificially low ack_wait, to show some messages // not getting acked being redelivered config: { durable_name: durable, ack_policy: AckPolicy.Explicit, ack_wait: nanos(4000), }, }); (async () => { for await (const m of psub) { console.log( `[${m.seq}] ${ m.redelivered ? `- redelivery ${m.info.redeliveryCount}` : "" }` ); if (m.seq % 2 === 0) { m.ack(); } } })(); const fn = () => { console.log("[PULL]"); psub.pull({ batch: 1000, expires: 10000 }); }; // do the initial pull fn(); // and now schedule a pull every so often const interval = setInterval(fn, 10000); // and repeat every 2s setTimeout(() => { clearInterval(interval); nc.drain(); }, 20000); ``` -------------------------------- ### Check NATS Connection Status - Ruby Source: https://github.com/nats-io/nats.docs/blob/master/_examples/connect_status.html An example using the Ruby NATS client to start a connection, check its status (`connected?`, `closing?`, `reconnecting?`), and stop the NATS server when the connection is closing. It uses EventMachine for timers. ```Ruby NATS.start(max_reconnect_attempts: 2) do |nc| puts "Connect is connected?: #{nc.connected?}" timer = EM.add_periodic_timer(1) do if nc.closing? puts "Connection closed..." EM.cancel_timer(timer) NATS.stop end if nc.reconnecting? puts "Reconnecting to NATS..." next end end end ``` -------------------------------- ### Start Lightweight Docker Container Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/running/nats_docker/ngs-docker-python.md Launches a basic Python 3.8 Docker container. Use this for a clean environment. ```shell docker run --entrypoint /bin/bash -it python:3.8-slim-buster ``` -------------------------------- ### Advanced Stream Configuration with Multiple Sources Source: https://github.com/nats-io/nats.docs/blob/master/nats-concepts/jetstream/source_and_mirror_example.md An enhanced JSON configuration for a NATS JetStream stream with multiple sources. This example includes filtering subjects, starting from specific message sequence numbers, and external API configurations for sources. ```json { "name": "SOURCE_TARGET", "subjects": [ "foo1.ext.*", "foo2.ext.*" ], "discard": "old", "duplicate_window": 120000000000, "sources": [ { "name": "SOURCE1_ORIGIN", "filter_subject": "foo1.bar", "opt_start_seq": 42, "external": { "deliver": "", "api": "$JS.domainA.API" } }, { "name": "SOURCE2_ORIGIN", "filter_subject": "foo2.bar" } ], "consumer_limits": { }, "deny_delete": false, "sealed": false, "max_msg_size": -1, "allow_rollup_hdrs": false, "max_bytes": -1, "storage": "file", "allow_direct": false, "max_age": 0, "max_consumers": -1, "max_msgs_per_subject": -1, "num_replicas": 1, "name": "SOURCE_TARGET", "deny_purge": false, "compression": "none", "max_msgs": -1, "retention": "limits", "mirror_direct": false } ``` -------------------------------- ### Download and Install NATS Server Manually Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/installation.md Steps to download a specific release archive from GitHub, extract the contents, and move the binary to the system path. ```shell curl -L https://github.com/nats-io/nats-server/releases/download/vX.Y.Z/nats-server-vX.Y.Z-linux-amd64.tar.gz -o nats-server.tar.gz tar -xvzf nats-server.tar.gz sudo cp nats-server-vX.Y.Z-linux-amd64/nats-server /usr/bin ``` -------------------------------- ### Get Max Payload Size with NATS Client Source: https://github.com/nats-io/nats.docs/blob/master/_examples/max_payload.html Demonstrates how to connect to a NATS server and retrieve the maximum payload size supported by the server. This is useful for understanding message size limitations. The examples cover multiple client libraries. ```Go nc, err := nats.Connect("demo.nats.io") if err != nil { log.Fatal(err) } defer nc.Close() mp := nc.MaxPayload() log.Printf("Maximum payload is %v bytes", mp) // Do something with the max payload ``` ```Java Connection nc = Nats.connect("nats://demo.nats.io:4222"); long max = nc.getMaxPayload(); // Do something with the max payload nc.close(); ``` ```JavaScript let nc = NATS.connect("nats://demo.nats.io:4222"); // on node you *must* register an error listener. If not registered // the library emits an 'error' event, the node process will exit. nc.on('error', (err) => { t.log('client got an error:', err); }); nc.on('connect', () => { t.log(nc.info.max_payload); }); ``` ```Python nc = NATS() await nc.connect(servers=["nats://demo.nats.io:4222"]) print("Maximum payload is %d bytes" % nc.max_payload) # Do something with the max payload. ``` ```Ruby require 'nats/client' NATS.start(max_outstanding_pings: 5) do |nc| nc.on_reconnect do puts "Got reconnected to #{nc.connected_server}" end nc.on_disconnect do |reason| puts "Got disconnected! #{reason}" end # Do something with the max_payload puts "Maximum Payload is #{nc.server_info[:max_payload]} bytes" end ``` ```TypeScript // connect will happen once - the first connect nc.on('connect', (nc: Client, url: string, options: ServerInfo) => { // nc is the connection that connected t.log('client connected to', url); t.log('max_payload', options.max_payload); }); ``` -------------------------------- ### Configure NATS TLS Connection Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/connecting/security/tls.md Examples of initializing a NATS client connection with TLS options, including CA files, client certificates, and private keys. These snippets show the necessary setup to ensure secure communication with a NATS server. ```csharp using NATS.Net; using NATS.Client.Core; await using var client = new NatsClient(new NatsOpts { TlsOpts = new NatsTlsOpts { CaFile = "rootCA.pem", KeyFile = "client-key.pem", CertFile = "client-cert.pem", } }); ``` ```ruby EM.run do options = { :servers => ['nats://localhost:4222'], :tls => { :private_key_file => 'client-key.pem', :cert_chain_file => 'client-cert.pem', :ca_file => 'rootCA.pem' } } NATS.connect(options) do |nc| # Connection logic here end end ``` ```c natsConnection *conn = NULL; natsOptions *opts = NULL; natsStatus s = NATS_OK; s = natsOptions_Create(&opts); if (s == NATS_OK) s = natsOptions_LoadCertificatesChain(opts, "client-cert.pem", "client-key.pem"); if (s == NATS_OK) s = natsOptions_LoadCATrustedCertificates(opts, "rootCA.pem"); if (s == NATS_OK) s = natsConnection_Connect(&conn, opts); natsConnection_Destroy(conn); natsOptions_Destroy(opts); ``` -------------------------------- ### Connect to Default NATS Server Source: https://github.com/nats-io/nats.docs/blob/master/_examples/connect_default.html Demonstrates how to connect to the default NATS server URL. This is a basic connection setup. Ensure the NATS server is running. ```Go nc, err := nats.Connect(nats.DefaultURL) if err != nil { log.Fatal(err) } defer nc.Close() // Do something with the connection ``` ```Java Connection nc = Nats.connect(); // Do something with the connection nc.close(); ``` ```JavaScript let nc = NATS.connect(); nc.on('connect', (c) => { // Do something with the connection doSomething(); // When done close it nc.close(); }); nc.on('error', (err) => { failed(err); }); ``` ```Python nc = NATS() await nc.connect() // Do something with the connection await nc.close() ``` ```Ruby require 'nats/client' NATS.start do |nc| # Do something with the connection # Close the connection nc.close end ``` ```TypeScript // will throw an exception if connection fails let nc = await connect(); // Do something with the connection // When done close it nc.close(); // alternatively, you can use the Promise pattern let nc1: Client; connect() .then((c) => { nc1 = c; // Do something with the connection nc1.close(); }); // add a .catch/.finally ``` -------------------------------- ### Connect to NATS with Pedantic Mode Enabled Source: https://github.com/nats-io/nats.docs/blob/master/_examples/connect_pedantic.html Demonstrates how to connect to a NATS server with pedantic mode enabled, which enforces stricter validation of messages. This example shows the basic connection setup and error handling for Go, Java, JavaScript, Python, Ruby, and TypeScript clients. ```Go opts := nats.GetDefaultOptions() opts.Url = "demo.nats.io" // Turn on Pedantic opts.Pedantic = true nc, err := opts.Connect() if err != nil { log.Fatal(err) } deffer nc.Close() // Do something with the connection ``` ```Java Options options = new Options.Builder(). server("nats://demo.nats.io:4222"). pedantic(). // Turn on pedantic build(); Connection nc = Nats.connect(options); // Do something with the connection nc.close(); ``` ```JavaScript let nc = NATS.connect({ url: "nats://demo.nats.io:4222", pedantic: true }); ``` ```Python nc = NATS() await nc.connect(servers=["nats://demo.nats.io:4222"], pedantic=True) # Do something with the connection. ``` ```Ruby require 'nats/client' NATS.start(pedantic: true) do |nc| nc.on_reconnect do puts "Got reconnected to #{nc.connected_server}" end nc.on_disconnect do |reason| puts "Got disconnected! #{reason}" end nc.close end ``` ```TypeScript // will throw an exception if connection fails let nc = await connect({ url: "nats://demo.nats.io:4222", pedantic: true }); nc.close(); ``` -------------------------------- ### Python Ordered Consumer Example Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/consumers.md Demonstrates creating an ordered consumer in Python with flow control and heartbeats, configured for auto-resumption on failures. ```python import asyncio import nats from nats.errors import TimeoutError async def main(): nc = await nats.connect("localhost") # Create JetStream context. js = nc.jetstream() # Create ordered consumer with flow control and heartbeats # that auto resumes on failures. osub = await js.subscribe("foo", ordered_consumer=True) data = bytearray() while True: try: msg = await osub.next_msg() data.extend(msg.data) except TimeoutError: break print("All data in stream:", len(data)) await nc.close() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### C# Ordered Consumer Example Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/js/consumers.md Provides an example of creating an ordered consumer in C# using the NATS.Net client library. It includes stream creation and publishing a message before setting up the consumer. ```csharp // dotnet add package NATS.Net using NATS.Net; using NATS.Client.JetStream; using NATS.Client.JetStream.Models; await using var client = new NatsClient(); INatsJSContext js = client.CreateJetStreamContext(); var streamConfig = new StreamConfig(name: "FOO", subjects: ["foo"]); await js.CreateStreamAsync(streamConfig); PubAckResponse ack = await js.PublishAsync("foo", "Hello, JetStream!"); ack.EnsureSuccess(); INatsJSConsumer orderedConsumer = await js.CreateOrderedConsumerAsync("FOO"); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); ``` -------------------------------- ### TypeScript NATS Subscriber Example Source: https://github.com/nats-io/nats.docs/blob/master/_examples/subscribe_arrow.html This TypeScript example shows how to subscribe to NATS subjects and handle messages, similar to the Node.js example. ```APIDOC ## POST /api/auth/login ### Description Authenticates a user and returns an access token. ### Method POST ### Endpoint /api/auth/login ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. ### Request Example ```json { "username": "johndoe", "password": "securepassword123" } ``` ### Response #### Success Response (200) - **accessToken** (string) - The JWT access token for authenticated requests. - **tokenType** (string) - The type of token (e.g., "Bearer"). #### Response Example ```json { "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...".", "tokenType": "Bearer" } ``` ``` -------------------------------- ### Start NATS Server with Configuration File Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/configuration/README.md Specify a custom configuration file for the NATS server using the `-config` flag. ```shell nats-server -config my-server.conf ``` -------------------------------- ### Install NATS Python Client and Dependencies Source: https://github.com/nats-io/nats.docs/blob/master/running-a-nats-service/running/nats_docker/ngs-docker-python.md Updates package lists and installs build essentials, curl, and the NATS Python client with NKeys support. Ensure you have build-essential and curl installed before running this. ```shell apt-get update && apt-get install -y build-essential curl pip install asyncio-nats-client[nkeys] ``` -------------------------------- ### Configure NATS Server Authentication Source: https://github.com/nats-io/nats.docs/blob/master/reference/nats-protocol/nats-protocol/nats-client-dev.md Demonstrates how to start a NATS server with user and password authentication via the command line. ```shell nats-server -DV -m 8222 -user foo -pass bar ``` -------------------------------- ### NATS Request-Reply Manual Implementation (Go) Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/sending/request_reply.md Illustrates a manual implementation of the request-reply pattern in Go, showing the underlying steps of subscribing, publishing a request with a reply-to subject, and waiting for a single message. Includes error handling and unsubscribing. ```Go sub, err := nc.SubscribeSync(replyTo) if err != nil { log.Fatal(err) } // Send the request immediately nc.PublishRequest(subject, replyTo, []byte(input)) nc.Flush() // Wait for a single response for { msg, err := sub.NextMsg(1 * time.Second) if err != nil { log.Fatal(err) } response = string(msg.Data) break } sub.Unsubscribe() ``` -------------------------------- ### C Request/Reply Example Source: https://github.com/nats-io/nats.docs/blob/master/using-nats/developing-with-nats/sending/replyto.md Provides an example of the request/reply pattern using the NATS C client library. ```APIDOC ## POST /api/request ### Description Sends a request message and waits for a single reply using C. ### Method POST ### Endpoint /api/request ### Parameters #### Query Parameters - **subject** (string) - Required - The subject to send the request to. - **reply_to** (string) - Required - The subject to listen for replies on. - **payload** (string) - Required - The message payload. ### Request Example ```json { "subject": "time", "reply_to": "INBOX.xyz", "payload": "" } ``` ### Response #### Success Response (200) - **reply** (string) - The reply message received. #### Response Example ```json { "reply": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Go - Discovered Servers Handler Source: https://github.com/nats-io/nats.docs/blob/master/_examples/servers_added.html This Go example demonstrates how to use the `nats.DiscoveredServersHandler` to be notified when new servers join the cluster and to log all known and discovered servers. ```APIDOC ## Go - Discovered Servers Handler ### Description This example shows how to set up a handler in the Go NATS client to be notified when new servers are discovered in the cluster. It logs the list of all known servers and the newly discovered ones. ### Method N/A (Event-driven callback) ### Endpoint N/A (Client-side configuration) ### Parameters N/A ### Request Example N/A ### Response N/A (Callback function is invoked) #### Success Response (Callback Invocation) - **Known servers**: `[]string` - A slice of strings representing all servers the client is aware of. - **Discovered servers**: `[]string` - A slice of strings representing the servers that were just discovered. #### Response Example ``` Known servers: ["nats://demo.nats.io:4222"] Discovered servers: ["nats://demo.nats.io:4222"] ``` ``` -------------------------------- ### Go NATS Subscriber Example Source: https://github.com/nats-io/nats.docs/blob/master/_examples/subscribe_arrow.html This Go example demonstrates how to subscribe to a NATS subject and process incoming messages. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new user resources. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address for the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **userId** (string) - The unique identifier for the newly created user. - **message** (string) - A confirmation message. #### Response Example ```json { "userId": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "message": "User created successfully" } ``` ```