### Install nk tool Source: https://docs.nats.io/using-nats/nats-tools/nk.md Installs the nk utility using the Go toolchain. ```bash go install github.com/nats-io/nkeys/nk@latest ``` -------------------------------- ### Install nats-top Source: https://docs.nats.io/using-nats/nats-tools/nats_top.md Install the tool using the Go toolchain. ```bash go install github.com/nats-io/nats-top ``` ```bash go install github.com/nats-io/nats-top@latest ``` -------------------------------- ### Install NATS Server from Source Source: https://docs.nats.io/running-a-nats-service/introduction/installation.md Use Go to install the latest development build from the main branch. ```shell go install github.com/nats-io/nats-server/v2@main ``` -------------------------------- ### NKey Output Example Source: https://docs.nats.io/running-a-nats-service/configuration/securing_nats/auth_intro/nkey_auth.md Example output showing the seed (private key) and public key. ```text SUACSSL3UAHUDXKFSNVUZRF5UHPMWZ6BFDTJ7M6USDXIEDNPPQYYYCU3VY UDXU4RCSJNZOIQHZNWXHXORDPRTGNJAHAHFRGZNEEJCPQTT2M7NLCNF4 ``` -------------------------------- ### Verify NATS installation Source: https://docs.nats.io/running-a-nats-service/introduction/installation.md Example output after running the nats-server command to verify the installation. ```text [41634] 2019/05/13 09:42:11.745919 [INF] Starting nats-server version 2.*.* [41634] 2019/05/13 09:42:11.746240 [INF] Listening for client connections on 0.0.0.0:4222 ... [41634] 2019/05/13 09:42:11.746249 [INF] Server id is NBNYNR4ZNTH4N2UQKSAAKBAFLDV3PZO4OUYONSUIQASTQT7BT4ZF6WX7 [41634] 2019/05/13 09:42:11.746252 [INF] Server is ready ``` -------------------------------- ### Synchronous Subscription Examples Source: https://docs.nats.io/using-nats/developer/receiving/sync.md Examples of creating a synchronous subscription and waiting for a message in Go, Java, and C. ```go nc, err := nats.Connect("demo.nats.io") if err != nil { log.Fatal(err) } defer nc.Close() // Subscribe sub, err := nc.SubscribeSync("updates") if err != nil { log.Fatal(err) } // Wait for a message msg, err := sub.NextMsg(10 * time.Second) if err != nil { log.Fatal(err) } // Use the response log.Printf("Reply: %s", msg.Data) ``` ```java Connection nc = Nats.connect("nats://demo.nats.io:4222"); // Subscribe Subscription sub = nc.subscribe("updates"); // Read a message Message msg = sub.nextMessage(Duration.ZERO); String str = new String(msg.getData(), StandardCharsets.UTF_8); System.out.println(str); // Close the connection nc.close(); ``` ```c natsConnection *conn = NULL; natsSubscription *sub = NULL; natsMsg *msg = NULL; natsStatus s = NATS_OK; s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL); // Subscribe if (s == NATS_OK) s = natsConnection_SubscribeSync(&sub, conn, "updates"); // Wait for messages if (s == NATS_OK) s = natsSubscription_NextMsg(&msg, sub, 10000); if (s == NATS_OK) { printf("Received msg: %s - %.*s\n", natsMsg_GetSubject(msg), natsMsg_GetDataLength(msg), natsMsg_GetData(msg)); // Destroy message that was received natsMsg_Destroy(msg); } (...) // Destroy objects that were created natsSubscription_Destroy(sub); natsConnection_Destroy(conn); ``` -------------------------------- ### Install and start NATS service Source: https://docs.nats.io/running-a-nats-service/introduction/windows_srv.md Use sc.exe to register the NATS server executable as a Windows service and start it. ```shell sc.exe create nats-server binPath= "%NATS_PATH%\nats-server.exe [nats-server flags]" sc.exe start nats-server ``` -------------------------------- ### Install NATS Server Source: https://docs.nats.io/using-nats/nats-tools/nsc/basics.md Install the NATS server using the Go toolchain. ```shell go get github.com/nats-io/nats-server ``` -------------------------------- ### KV get benchmark output Source: https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench.md Example output for the KV getter benchmark. ```text 14:28:33 Starting JetStream KV getter benchmark [bucket=benchbucket, clients=16, msg-size=128 B, msgs=100,000, randomize=100,000, sleep=0s] 14:28:33 [1] Starting JetStream KV getter, trying to get 6,250 messages 14:28:33 [2] Starting JetStream KV getter, trying to get 6,250 messages ... 14:28:33 [15] Starting JetStream KV getter, trying to get 6,250 messages 14:28:33 [16] Starting JetStream KV getter, trying to get 6,250 messages [1] 6,568 msgs/sec ~ 821 KiB/sec ~ 152.23us (6,250 msgs) [2] 6,579 msgs/sec ~ 822 KiB/sec ~ 151.98us (6,250 msgs) ... [15] 6,474 msgs/sec ~ 809 KiB/sec ~ 154.45us (6,250 msgs) [16] 6,451 msgs/sec ~ 806 KiB/sec ~ 155.01us (6,250 msgs) NATS JetStream KV getter aggregated stats: 102,844 msgs/sec ~ 13 MiB/sec message rates min 6,448 | avg 6,509 | max 6,579 | stddev 40 msgs avg latencies min 151.98us | avg 153.61us | max 155.08us | stddev 0.96us ``` -------------------------------- ### Request-Reply Implementation Examples Source: https://docs.nats.io/using-nats/developer/sending/request_reply.md Examples demonstrating how to perform a request-reply operation across various NATS client libraries. ```go nc, err := nats.Connect("demo.nats.io") if err != nil { log.Fatal(err) } defer nc.Close() // Send the request msg, err := nc.Request("time", nil, time.Second) if err != nil { log.Fatal(err) } // Use the response log.Printf("Reply: %s", msg.Data) // Close the connection nc.Close() ``` ```java Connection nc = Nats.connect("nats://demo.nats.io:4222"); // set up a listener for "time" requests Dispatcher d = nc.createDispatcher(msg -> { System.out.println("Received time request"); nc.publish(msg.getReplyTo(), ("" + System.currentTimeMillis()).getBytes()); }); d.subscribe("time"); // make a request to the "time" subject and wait 1 second for a response Message msg = nc.request("time", null, Duration.ofSeconds(1)); // look at the response long time = Long.parseLong(new String(msg.getData())); System.out.println(new Date(time)); nc.close(); ``` ```javascript // set up a subscription to process the request const sc = StringCodec(); nc.subscribe("time", { callback: (_err, msg) => { msg.respond(sc.encode(new Date().toLocaleTimeString())); }, }); const r = await nc.request("time"); t.log(sc.decode(r.data)); ``` ```python nc = NATS() async def sub(msg): await nc.publish(msg.reply, b'response') await nc.connect(servers=["nats://demo.nats.io:4222"]) await nc.subscribe("time", cb=sub) # Send the request try: msg = await nc.request("time", b'', timeout=1) # Use the response print("Reply:", msg) except asyncio.TimeoutError: print("Timed out waiting for response") ``` ```csharp // dotnet add package NATS.Net using NATS.Net; await using var client = new NatsClient(); using CancellationTokenSource cts = new(); // Process the time messages in a separate task Task subscription = Task.Run(async () => { await foreach (var msg in client.SubscribeAsync("time", cancellationToken: cts.Token)) { await msg.ReplyAsync(DateTimeOffset.Now); } }); // Wait for the subscription task to be ready await Task.Delay(1000); var reply = await client.RequestAsync("time"); Console.WriteLine($"Reply: {reply.Data:O}"); await cts.CancelAsync(); await subscription; // Output: // Reply: 2024-10-23T05:20:55.0000000+01:00 ``` ```ruby require 'nats/client' require 'fiber' NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc| nc.subscribe("time") do |msg, reply| nc.publish(reply, "response") end Fiber.new do # Use the response msg = nc.request("time", "") puts "Reply: #{msg}" end.resume end ``` ```c natsConnection *conn = NULL; natsMsg *msg = NULL; natsStatus s = NATS_OK; s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL); // Send a request and wait for up to 1 second if (s == NATS_OK) s = natsConnection_RequestString(&msg, conn, "request", "this is the request", 1000); if (s == NATS_OK) { printf("Received msg: %s - %.*s\n", natsMsg_GetSubject(msg), natsMsg_GetDataLength(msg), natsMsg_GetData(msg)); // Destroy the message that was received natsMsg_Destroy(msg); } (...) // Destroy objects that were created natsConnection_Destroy(conn); ``` -------------------------------- ### Start Leaf Node Server Source: https://docs.nats.io/running-a-nats-service/configuration/leafnodes.md Command to start the leaf node server using its configuration file. ```bash nats-server -c /tmp/leaf.conf ``` -------------------------------- ### Generate and use self-signed certificates with mkcert Source: https://docs.nats.io/running-a-nats-service/configuration/securing_nats/tls.md Installs the local CA and generates server certificates for localhost and IPv6 loopback, then starts the NATS server with TLS enabled. ```bash mkcert -install mkcert -cert-file server-cert.pem -key-file server-key.pem localhost ::1 nats-server --tls --tlscert=server-cert.pem --tlskey=server-key.pem -ms 8222 ``` -------------------------------- ### NATS configuration syntax examples Source: https://docs.nats.io/running-a-nats-service/configuration.md Examples of supported syntax elements including comments, assignments, arrays, and maps. ```text # Lines can be commented with # and // // Lines can be commented with # and // foo = 2 foo: 2 foo 2 ["a", "b", "c"] {foo: 2} accounts { SYS {...}, cloud-user {...} } host: 127.0.0.1; port: 4222; ``` -------------------------------- ### Install NATS CLI Tools Source: https://docs.nats.io/running-a-nats-service/nats_admin/security/jwt.md Commands to install the necessary NATS server and CLI utilities via Go. ```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 JetStream asynchronous publisher benchmark Source: https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench.md Starts 8 clients to perform asynchronous publications to a stream. ```bash nats bench js pub async jsfoo --clients 8 --no-progress ``` -------------------------------- ### Queue Subscription Examples Source: https://docs.nats.io/using-nats/developer/receiving/queues.md Examples demonstrating how to subscribe to a subject with a queue group name across different NATS client libraries. ```go nc, err := nats.Connect("demo.nats.io") if err != nil { log.Fatal(err) } defer nc.Close() // Use a WaitGroup to wait for 10 messages to arrive wg := sync.WaitGroup{} wg.Add(10) // Create a queue subscription on "updates" with queue name "workers" if _, err := nc.QueueSubscribe("updates", "workers", func(m *nats.Msg) { wg.Done() }); err != nil { log.Fatal(err) } // Wait for messages to come in wg.Wait() ``` ```java Connection nc = Nats.connect("nats://demo.nats.io:4222"); // Use a latch to wait for 10 messages to arrive CountDownLatch latch = new CountDownLatch(10); // Create a dispatcher and inline message handler Dispatcher d = nc.createDispatcher((msg) -> { String str = new String(msg.getData(), StandardCharsets.UTF_8); System.out.println(str); latch.countDown(); }); // Subscribe to the "updates" subject with a queue group named "workers" d.subscribe("updates", "workers"); // Wait for a message to come in latch.await(); // Close the connection nc.close(); ``` ```javascript nc.subscribe(subj, { queue: "workers", callback: (_err, _msg) => { t.log("worker1 got message"); }, }); nc.subscribe(subj, { queue: "workers", callback: (_err, _msg) => { t.log("worker2 got message"); }, }); ``` ```python nc = NATS() await nc.connect(servers=["nats://demo.nats.io:4222"]) future = asyncio.Future() async def cb(msg): nonlocal future future.set_result(msg) await nc.subscribe("updates", queue="workers", cb=cb) await nc.publish("updates", b'All is Well') msg = await asyncio.wait_for(future, 1) print("Msg", msg) ``` ```csharp // dotnet add package NATS.Net using NATS.Net; await using var client = new NatsClient(); var count = 0; // Subscribe to the "updates" subject with a queue group named "workers" await foreach (var msg in client.SubscribeAsync(subject: "updates", queueGroup: "workers")) { Console.WriteLine($"Received {++count}: {msg.Subject}: {msg.Data}"); // Break after 10 messages if (count == 10) { break; } } Console.WriteLine("Done"); ``` ```ruby require 'nats/client' require 'fiber' NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc| Fiber.new do f = Fiber.current nc.subscribe("updates", queue: "worker") do |msg, reply| f.resume Time.now end nc.publish("updates", "A") # Use the response msg = Fiber.yield puts "Msg: #{msg}" end.resume end ``` ```c static void onMsg(natsConnection *conn, natsSubscription *sub, natsMsg *msg, void *closure) { printf("Received msg: %s - %.*s\n", natsMsg_GetSubject(msg), natsMsg_GetDataLength(msg), natsMsg_GetData(msg)); // Need to destroy the message! natsMsg_Destroy(msg); } (...) natsConnection *conn = NULL; natsSubscription *sub = NULL; natsStatus s; s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL); // Create a queue subscription on "updates" with queue name "workers" if (s == NATS_OK) s = natsConnection_QueueSubscribe(&sub, conn, "updates", "workers", onMsg, NULL); (...) // Destroy objects that were created natsSubscription_Destroy(sub); natsConnection_Destroy(conn); ``` -------------------------------- ### Download NATS Python examples Source: https://docs.nats.io/running-a-nats-service/nats_docker/ngs-docker-python.md Retrieves standard NATS publish and subscribe example scripts using curl. ```shell curl -o nats-pub.py -O -L https://raw.githubusercontent.com/nats-io/nats.py/master/examples/nats-pub/__main__.py curl -o nats-sub.py -O -L https://raw.githubusercontent.com/nats-io/nats.py/master/examples/nats-sub/__main__.py ``` -------------------------------- ### Start JetStream ordered consumer benchmark Source: https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench.md Starts an ordered consumer with 8 clients to consume messages from a stream. ```bash nats bench js ordered --purge --clients 8 --no-progress ``` -------------------------------- ### Install NATS Python client Source: https://docs.nats.io/running-a-nats-service/nats_docker/ngs-docker-python.md Installs the necessary build tools and the nats.py library with nkeys support. ```shell apt-get update && apt-get install -y build-essential curl pip install asyncio-nats-client[nkeys] ``` -------------------------------- ### Example manual NATS server configuration Source: https://docs.nats.io/running-a-nats-service/configuration/securing_nats/auth_intro/jwt/mem_resolver.md A concrete example of a manual configuration file referencing an operator JWT and an account JWT. ```text operator: /Users/synadia/.nsc/nats/memory/memory.jwt resolver: MEMORY resolver_preload: { ACSU3Q6LTLBVLGAQUONAGXJHVNWGSKKAUA7IY5TB4Z7PLEKSR5O6JTGR: eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJPRFhJSVI2Wlg1Q1AzMlFJTFczWFBENEtTSDYzUFNNSEZHUkpaT05DR1RLVVBISlRLQ0JBIiwiaWF0IjoxNTU2NjU1Njk0LCJpc3MiOiJPRFdaSjJLQVBGNzZXT1dNUENKRjZCWTRRSVBMVFVJWTRKSUJMVTRLM1lERzNHSElXQlZXQkhVWiIsIm5hbWUiOiJBIiwic3ViIjoiQUNTVTNRNkxUTEJWTEdBUVVPTkFHWEpIVk5XR1NLS0FVQTdJWTVUQjRaN1BMRUtTUjVPNkpUR1IiLCJ0eXBlIjoiYWNjb3VudCIsIm5hdHMiOnsibGltaXRzIjp7InN1YnMiOi0xLCJjb25uIjotMSwibGVhZiI6LTEsImltcG9ydHMiOi0xLCJleHBvcnRzIjotMSwiZGF0YSI6LTEsInBheWxvYWQiOi0xLCJ3aWxkY2FyZHMiOnRydWV9fX0._WW5C1triCh8a4jhyBxEZZP8RJ17pINS8qLzz-01o6zbz1uZfTOJGvwSTS6Yv2_849B9iUXSd-8kp1iMXHdoBA } ``` -------------------------------- ### nats-top initial output Source: https://docs.nats.io/using-nats/nats-tools/nats_top/nats-top-tutorial.md Example output displayed by nats-top upon startup. ```text nats-server version 0.6.6 (uptime: 2m2s) Server: Load: CPU: 0.0% Memory: 6.3M Slow Consumers: 0 In: Msgs: 0 Bytes: 0 Msgs/Sec: 0.0 Bytes/Sec: 0 Out: Msgs: 0 Bytes: 0 Msgs/Sec: 0.0 Bytes/Sec: 0 Connections: 0 HOST CID SUBS PENDING MSGS_TO MSGS_FROM BYTES_TO BYTES_FROM LANG VERSION ``` -------------------------------- ### Connect Client with Credentials Source: https://docs.nats.io/reference/reference-protocols/nats-protocol/nats-client-dev.md Example of a client connection string including authentication credentials. ```go nats.Connect("nats://foo:bar@localhost:4222") ``` -------------------------------- ### Verify TLS server startup logs Source: https://docs.nats.io/running-a-nats-service/configuration/securing_nats/tls.md Example output showing the server confirming that TLS is required for client connections. ```text [21417] 2019/05/16 11:21:19.801539 [INF] Starting nats-server version 2.0.0 [21417] 2019/05/16 11:21:19.801621 [INF] Git commit [not set] [21417] 2019/05/16 11:21:19.801777 [INF] Listening for client connections on 0.0.0.0:4222 [21417] 2019/05/16 11:21:19.801782 [INF] TLS required for client connections [21417] 2019/05/16 11:21:19.801785 [INF] Server id is ND6ZZDQQDGKYQGDD6QN2Y26YEGLTH6BMMOJZ2XJB2VASPVII3XD6RFOQ [21417] 2019/05/16 11:21:19.801787 [INF] Server is ready ``` -------------------------------- ### Start NATS Server with Monitoring Source: https://docs.nats.io/running-a-nats-service/configuration/monitoring.md Example command to start the NATS server with the monitoring port set to 8222. ```bash nats-server -m 8222 ``` -------------------------------- ### NATS server gateway initialization logs Source: https://docs.nats.io/running-a-nats-service/configuration/gateways/gateway.md Example output showing the server initializing gateway connections and registering peers. ```text [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 ``` -------------------------------- ### Disable Echo in NATS Clients Source: https://docs.nats.io/using-nats/developer/connecting/noecho.md Examples of configuring the NoEcho option across various NATS client libraries during connection setup. ```go // Turn off echo nc, err := nats.Connect("demo.nats.io", nats.Name("API NoEcho Example"), nats.NoEcho()) if err != nil { log.Fatal(err) } defer nc.Close() // Do something with the connection ``` ```java Options options = new Options.Builder() .server("nats://demo.nats.io:4222") .noEcho() // Turn off echo .build(); Connection nc = Nats.connect(options); // Do something with the connection nc.close(); ``` ```javascript const nc = await connect({ servers: ["demo.nats.io"], noEcho: true, }); const sub = nc.subscribe(subj, { callback: (_err, _msg) => {} }); nc.publish(subj); await sub.drain(); // we won't get our own messages t.is(sub.getProcessed(), 0); ``` ```python ncA = NATS() ncB = NATS() await ncA.connect(no_echo=True) await ncB.connect() async def handler(msg): # Messages sent by `ncA' will not be received. print("[Received] ", msg) await ncA.subscribe("greetings", cb=handler) await ncA.flush() await ncA.publish("greetings", b'Hello World!') await ncB.publish("greetings", b'Hello World!') # Do something with the connection await asyncio.sleep(1) await ncA.drain() await ncB.drain() ``` ```csharp // dotnet add package NATS.Net using NATS.Net; using NATS.Client.Core; await using var client = new NatsClient(new NatsOpts { Url = "nats://demo.nats.io:4222", // Turn off echo Echo = false }); ``` ```ruby NATS.start("nats://demo.nats.io:4222", no_echo: true) do |nc| # ... end ``` ```c natsConnection *conn = NULL; natsOptions *opts = NULL; natsStatus s = NATS_OK; s = natsOptions_Create(&opts); if (s == NATS_OK) s = natsOptions_SetNoEcho(opts, true); if (s == NATS_OK) s = natsConnection_Connect(&conn, opts); (...) // Destroy objects that were created natsConnection_Destroy(conn); natsOptions_Destroy(opts); ``` -------------------------------- ### Start a NATS server with a configuration file Source: https://docs.nats.io/running-a-nats-service/configuration/gateways/gateway.md Launch the server using the specified configuration file. ```shell nats-server -c A.conf ``` -------------------------------- ### Create an Object Store Bucket Source: https://docs.nats.io/nats-concepts/jetstream/obj_store/obj_walkthrough.md Initialize a new Object Store bucket named 'myobjbucket'. ```shell nats object add myobjbucket ``` -------------------------------- ### Archive Output Example Source: https://docs.nats.io/running-a-nats-service/introduction/installation.md Example output showing the contents of an extracted archive. ```text Archive: nats-server.zip creating: nats-server-vX.Y.Z-linux-amd64/ ... ``` -------------------------------- ### Add activation revocation example Source: https://docs.nats.io/running-a-nats-service/nats_admin/security/jwt.md Example command to revoke an activation for a specific account. ```shell nsc revocations add-activation --account SYS --subject foo \ --target-account AAUDEW26FB4TOJAQN3DYMDLCVXZMNIJWP2EMOAM5HGKLF6RGMO2PV7WP ``` -------------------------------- ### Build NATS Server from Source Source: https://docs.nats.io/running-a-nats-service/introduction/installation.md Commands to install goreleaser, clone the repository, and execute a local build. ```bash go install github.com/goreleaser/goreleaser/v2@latest git clone git@github.com:nats-io/nats-server.git cd nats-server git checkout v2.12.0 [[ `git status --porcelain` ]] && echo "Must have repo in clean state before building" goreleaser release --skip=announce,publish,validate --clean -f .goreleaser.yml ``` -------------------------------- ### Benchmark JetStream Batched Get Source: https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench.md Measures throughput using batched direct gets. ```bash nats bench js get batch --clients 2 ``` ```text 14:11:09 Starting JetStream batched direct getter benchmark [batch=500, clients=2, filter=>, msg-size=128 B, msgs=100,000, sleep=0s, stream=benchstream] 14:11:09 [1] Starting JetStream batched direct getter, expecting 100,000 messages 14:11:09 [2] Starting JetStream batched direct getter, expecting 100,000 messages Finished 0s [================================================================] 100% Finished 0s [================================================================] 100% [1] 509,387 msgs/sec ~ 62 MiB/sec ~ 1.96us (100,000 msgs) [2] 500,449 msgs/sec ~ 61 MiB/sec ~ 2.00us (100,000 msgs) NATS JetStream batched direct getter aggregated stats: 1,000,898 msgs/sec ~ 122 MiB/sec message rates min 500,449 | avg 504,918 | max 509,387 | stddev 4,469 msgs avg latencies min 1.96us | avg 1.98us | max 2.00us | stddev 0.02us ``` -------------------------------- ### GET /running-a-nats-service/introduction/installation.md Source: https://docs.nats.io/running-a-nats-service/introduction/installation.md Performs a query against the documentation to retrieve answers based on a specific question and optional goal. ```APIDOC ## GET /running-a-nats-service/introduction/installation.md ### Description Queries the documentation for information by providing a natural language question and an optional end goal. ### Method GET ### Endpoint https://docs.nats.io/running-a-nats-service/introduction/installation.md ### Parameters #### Query Parameters - **ask** (string) - Required - The specific, self-contained question to ask. - **goal** (string) - Optional - The broader end goal to help tailor the response. ``` -------------------------------- ### Implementing JetStream Consumers in C Source: https://docs.nats.io/using-nats/developer/develop_jetstream/consumers.md A complete example showing stream initialization, subscription configuration, and message processing for pull, async, and sync consumers. ```c 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 (%" 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); } ``` -------------------------------- ### Measure KV get performance Source: https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench.md Command to initiate a Key-Value get benchmark with 16 clients. ```bash nats bench kv get --clients 16 --randomize 100000 --no-progress ``` -------------------------------- ### Create a new account Source: https://docs.nats.io/using-nats/nats-tools/nsc/streams.md Initializes a new account named B. ```bash nsc add account B ``` -------------------------------- ### NATS Server Startup Log Source: https://docs.nats.io/running-a-nats-service/nats_admin/security/jwt.md Example output showing a NATS server initialized with an operator and JWT directory. ```text [2] 30129 [30129] 2020/11/04 14:30:14.062132 [INF] Starting nats-server version 2.2.0-beta.26 [30129] 2020/11/04 14:30:14.062215 [INF] Git commit [not set] [30129] 2020/11/04 14:30:14.062219 [INF] Using configuration file: nats-res.cfg [30129] 2020/11/04 14:30:14.062220 [INF] Trusted Operators [30129] 2020/11/04 14:30:14.062224 [INF] System : "" [30129] 2020/11/04 14:30:14.062226 [INF] Operator: "DEMO" [30129] 2020/11/04 14:30:14.062241 [INF] Issued : 2020-11-04 14:25:25 -0500 EST [30129] 2020/11/04 14:30:14.062244 [INF] Expires : 1969-12-31 19:00:00 -0500 EST [30129] 2020/11/04 14:30:14.062652 [INF] Managing all jwt in exclusive directory /demo/env1/jwt [30129] 2020/11/04 14:30:14.065888 [INF] Listening for client connections on localhost:4222 [30129] 2020/11/04 14:30:14.065896 [INF] Server id is NBQ6AG5YIRC6PRCUPCAUSVCSCQWAAWW2XQXIM6UPW5AFPGZBUKZJTRRS [30129] 2020/11/04 14:30:14.065898 [INF] Server name is NBQ6AG5YIRC6PRCUPCAUSVCSCQWAAWW2XQXIM6UPW5AFPGZBUKZJTRRS [30129] 2020/11/04 14:30:14.065900 [INF] Server is ready > ``` -------------------------------- ### Verify NATS Server Installation Source: https://docs.nats.io/running-a-nats-service/introduction/installation.md Run the server command to verify the installation and view startup logs. ```text [2397474] 2023/09/27 10:32:02.709019 [INF] Starting nats-server [2397474] 2023/09/27 10:32:02.709165 [INF] Version: 2.11.0-dev [2397474] 2023/09/27 10:32:02.709182 [INF] Git: [not set] [2397474] 2023/09/27 10:32:02.709185 [INF] Name: NDQU7SGA4ECW4PHL4KNBY42AFQEZDAPMMQZVSQDKGTARZI5JHJV6KO2N [2397474] 2023/09/27 10:32:02.709187 [INF] ID: NDQU7SGA4ECW4PHL4KNBY42AFQEZDAPMMQZVSQDKGTARZI5JHJV6KO2N [2397474] 2023/09/27 10:32:02.709795 [INF] Listening for client connections on 0.0.0.0:4222 [2397474] 2023/09/27 10:32:02.710173 [INF] Server is ready ``` -------------------------------- ### NATS Server Startup Output Source: https://docs.nats.io/nats-concepts/what-is-nats/walkthrough_setup.md Example log output indicating a successful NATS server startup. ```text [14524] 2021/10/25 22:53:53.525530 [INF] Starting nats-server [14524] 2021/10/25 22:53:53.525640 [INF] Version: 2.6.1 [14524] 2021/10/25 22:53:53.525643 [INF] Git: [not set] [14524] 2021/10/25 22:53:53.525647 [INF] Name: NDAUZCA4GR3FPBX4IFLBS4VLAETC5Y4PJQCF6APTYXXUZ3KAPBYXLACC [14524] 2021/10/25 22:53:53.525650 [INF] ID: NDAUZCA4GR3FPBX4IFLBS4VLAETC5Y4PJQCF6APTYXXUZ3KAPBYXLACC [14524] 2021/10/25 22:53:53.526392 [INF] Starting http monitor on 0.0.0.0:8222 [14524] 2021/10/25 22:53:53.526445 [INF] Listening for client connections on 0.0.0.0:4222 [14524] 2021/10/25 22:53:53.526684 [INF] Server is ready ``` -------------------------------- ### Install service with log file Source: https://docs.nats.io/running-a-nats-service/introduction/windows_srv.md Configure the service to write logs to a specific file path to avoid console logging issues. ```shell sc.exe create nats-server binPath= "%NATS_PATH%\nats-server.exe --log C:\temp\nats-server.log [other flags]" ``` -------------------------------- ### CONNECT Message Example Source: https://docs.nats.io/reference/reference-protocols/nats-server-protocol.md Example of a CONNECT message sent by a server to provide connection and security details. ```text CONNECT {"tls_required":false,"name":"wt0vffeQyoDGMVBC2aKX0b"} ``` -------------------------------- ### Start NATS Server Standalone Source: https://docs.nats.io/running-a-nats-service/introduction/running.md Starts the NATS server with default settings, listening on port 4222. ```shell nats-server ``` ```text [61052] 2021/10/28 16:53:38.003205 [INF] Starting nats-server [61052] 2021/10/28 16:53:38.003329 [INF] Version: 2.6.1 [61052] 2021/10/28 16:53:38.003333 [INF] Git: [not set] [61052] 2021/10/28 16:53:38.003339 [INF] Name: NDUP6JO4T5LRUEXZUHWXMJYMG4IZAJDNWETTA4GPJ7DKXLJUXBN3UP3M [61052] 2021/10/28 16:53:38.003342 [INF] ID: NDUP6JO4T5LRUEXZUHWXMJYMG4IZAJDNWETTA4GPJ7DKXLJUXBN3UP3M [61052] 2021/10/28 16:53:38.004046 [INF] Listening for client connections on 0.0.0.0:4222 [61052] 2021/10/28 16:53:38.004683 [INF] Server is ready ... ``` -------------------------------- ### Start a basic request-reply service Source: https://docs.nats.io/using-nats/nats-tools/nats_cli/natsbench.md Run a service instance to listen for requests on the specified subject. ```bash nats bench service serve foo ``` -------------------------------- ### Install NSC Tool Source: https://docs.nats.io/using-nats/nats-tools/nsc.md Use the provided Python script to download and install the latest version of the NSC tool. ```shell curl -L https://raw.githubusercontent.com/nats-io/nsc/master/install.py | python ``` -------------------------------- ### Install NATS via package managers Source: https://docs.nats.io/running-a-nats-service/introduction/installation.md Commands to install the nats-server package on Windows, macOS, and Arch Linux. ```shell scoop install main/nats-server ``` ```shell brew install nats-server ``` ```shell yay -S nats-server ```