### Run Example via Classpath Source: https://github.com/nats-io/nats.java/blob/main/examples/src/main/java/io/nats/examples/README.md Execute a NATS example class using the generated Uber Jar. ```bash java -cp build/libs/java-nats-{major.minor.patch}-SNAPSHOT-uber.jar io.nats.examples.NatsPub nats://localhost:4222 test "hello world" ``` -------------------------------- ### Run NATS Java Subscribe Example Source: https://github.com/nats-io/nats.java/blob/main/examples/src/main/java/io/nats/examples/natsIoDoc/README.md Runs the BasicsSubscribe example using the generated Uber JAR. This example demonstrates how to subscribe to a NATS subject. ```bash java -cp build/libs/java-nats-{major.minor.patch}-SNAPSHOT-uber.jar io.nats.examples.natsIoDoc.BasicsSubscribe ``` -------------------------------- ### Run NATS Subscriber Example Source: https://github.com/nats-io/nats.java/blob/main/README.md Executes the NatsSub example class using the built Uber Jar. This demonstrates how to run a NATS subscriber from the command line. ```bash java -cp build/libs/java-nats-2.25.4-SNAPSHOT-uber.jar io.nats.examples.NatsSub ``` -------------------------------- ### NATS Properties File Example Source: https://github.com/nats-io/nats.java/blob/main/README.md Demonstrates equivalent property configurations for NATS servers, showing both prefixed and non-prefixed versions. ```properties io.nats.client.servers=nats://localhost:4222 ``` ```properties servers=nats://localhost:4222 ``` -------------------------------- ### Start the NATS compatibility responder Source: https://github.com/nats-io/nats.java/blob/main/src/test/java/io/nats/compatibility/README.md Execute the main compatibility class using the classpath containing main and test classes. ```shell > java -cp build/classes/java/main;build/classes/java/test io.nats.compatibility.ClientCompatibilityMain ``` -------------------------------- ### Start NATS Server with TLS Config Source: https://github.com/nats-io/nats.java/blob/main/examples/src/main/java/io/nats/examples/README.md Launch the NATS server using specific TLS configuration files. ```bash nats-server --config src/test/resources/tls.conf ``` ```bash nats-server --config src/test/resources/tlsverify.conf ``` -------------------------------- ### Basic Subscribe Subject Example Source: https://github.com/nats-io/nats.java/blob/main/README.md A basic example of subscribing to a subject using the JetStream client. The subject is required for ephemeral consumers. ```java JetStream js = nc.jetStream(); JetStreamSubscription sub = subscribe(subject) ``` -------------------------------- ### Build NATS Java Uber Jar Source: https://github.com/nats-io/nats.java/blob/main/examples/src/main/java/io/nats/examples/natsIoDoc/README.md Builds an Uber JAR for the NATS Java client examples. This JAR includes all dependencies and can be used to run the examples from the command line. ```bash gradlew clean uberJar ``` -------------------------------- ### NatsBench Benchmark Results Source: https://github.com/nats-io/nats.java/blob/main/README.md Example output from the NatsBench tool, demonstrating publish-only and publish-subscribe performance metrics. This tool runs tests with a fixed number of threads and connections. ```AsciiDoc Starting benchmark(s) [msgs=5000000, msgsize=256, pubs=2, subs=2] Current memory usage is 966.14 mb / 981.50 mb / 14.22 gb free/total/max Use ctrl-C to cancel. Pub Only stats: 9,584,263 msgs/sec ~ 2.29 gb/sec [ 1] 4,831,495 msgs/sec ~ 1.15 gb/sec (2500000 msgs) [ 2] 4,792,145 msgs/sec ~ 1.14 gb/sec (2500000 msgs) min 4,792,145 | avg 4,811,820 | max 4,831,495 | stddev 19,675.00 msgs Pub/Sub stats: 3,735,744 msgs/sec ~ 912.05 mb/sec Pub stats: 1,245,680 msgs/sec ~ 304.12 mb/sec [ 1] 624,385 msgs/sec ~ 152.44 mb/sec (2500000 msgs) [ 2] 622,840 msgs/sec ~ 152.06 mb/sec (2500000 msgs) min 622,840 | avg 623,612 | max 624,385 | stddev 772.50 msgs Sub stats: 2,490,461 msgs/sec ~ 608.02 mb/sec [ 1] 1,245,230 msgs/sec ~ 304.01 mb/sec (5000000 msgs) [ 2] 1,245,231 msgs/sec ~ 304.01 mb/sec (5000000 msgs) min 1,245,230 | avg 1,245,230 | max 1,245,231 | stddev .71 msgs Final memory usage is 2.02 gb / 2.94 gb / 14.22 gb free/total/max ``` -------------------------------- ### NatsAutoBench Performance Results by Message Size Source: https://github.com/nats-io/nats.java/blob/main/README.md Example output from the NatsAutoBench tool, showcasing performance across various message sizes for publish-only, publish-subscribe, and request-reply scenarios. This tool is useful for understanding throughput and latency trade-offs with different message payloads. ```AsciiDoc PubOnly 0b 10,000,000 8,464,850 msg/s 0.00 b/s PubOnly 8b 10,000,000 10,065,263 msg/s 76.79 mb/s PubOnly 32b 10,000,000 12,534,612 msg/s 382.53 mb/s PubOnly 256b 10,000,000 7,996,057 msg/s 1.91 gb/s PubOnly 512b 10,000,000 5,942,165 msg/s 2.83 gb/s PubOnly 1k 1,000,000 4,043,937 msg/s 3.86 gb/s PubOnly 4k 500,000 1,114,947 msg/s 4.25 gb/s PubOnly 8k 100,000 460,630 msg/s 3.51 gb/s PubSub 0b 10,000,000 3,155,673 msg/s 0.00 b/s PubSub 8b 10,000,000 3,218,427 msg/s 24.55 mb/s PubSub 32b 10,000,000 2,681,550 msg/s 81.83 mb/s PubSub 256b 10,000,000 2,020,481 msg/s 493.28 mb/s PubSub 512b 5,000,000 2,000,918 msg/s 977.01 mb/s PubSub 1k 1,000,000 1,170,448 msg/s 1.12 gb/s PubSub 4k 100,000 382,964 msg/s 1.46 gb/s PubSub 8k 100,000 196,474 msg/s 1.50 gb/s PubDispatch 0b 10,000,000 4,645,438 msg/s 0.00 b/s PubDispatch 8b 10,000,000 4,500,006 msg/s 34.33 mb/s PubDispatch 32b 10,000,000 4,458,481 msg/s 136.06 mb/s PubDispatch 256b 10,000,000 2,586,563 msg/s 631.49 mb/s PubDispatch 512b 5,000,000 2,187,592 msg/s 1.04 gb/s PubDispatch 1k 1,000,000 1,369,985 msg/s 1.31 gb/s PubDispatch 4k 100,000 403,314 msg/s 1.54 gb/s PubDispatch 8k 100,000 203,320 msg/s 1.55 gb/s ReqReply 0b 20,000 9,548 msg/s 0.00 b/s ReqReply 8b 20,000 9,491 msg/s 74.15 kb/s ReqReply 32b 10,000 9,778 msg/s 305.59 kb/s ReqReply 256b 10,000 8,394 msg/s 2.05 mb/s ReqReply 512b 10,000 8,259 msg/s 4.03 mb/s ReqReply 1k 10,000 8,193 msg/s 8.00 mb/s ReqReply 4k 10,000 7,915 msg/s 30.92 mb/s ReqReply 8k 10,000 7,454 msg/s 58.24 mb/s Latency 0b 5,000 35 / 49.20 / 134 +/- 0.77 (microseconds) Latency 8b 5,000 35 / 49.54 / 361 +/- 0.80 (microseconds) Latency 32b 5,000 35 / 49.27 / 135 +/- 0.79 (microseconds) Latency 256b 5,000 41 / 56.41 / 142 +/- 0.90 (microseconds) Latency 512b 5,000 40 / 56.41 / 174 +/- 0.91 (microseconds) Latency 1k 5,000 35 / 49.76 / 160 +/- 0.80 (microseconds) Latency 4k 5,000 36 / 50.64 / 193 +/- 0.83 (microseconds) Latency 8k 5,000 38 / 55.45 / 206 +/- 0.88 (microseconds) ``` -------------------------------- ### Configure NATS Connection with Options in Java Source: https://github.com/nats-io/nats.java/blob/main/src/main/javadoc/overview.html Example of configuring advanced connection options for NATS, including server address, security, and buffer size. Requires the NATS Java client library. ```java Options o = new Options.Builder().server("nats://hostname:4222").secure().reconnectBufferSize(300).build(); Connection nc = Nats.connect(o); ``` -------------------------------- ### Publish a Message with NATS Java Source: https://github.com/nats-io/nats.java/blob/main/src/main/javadoc/overview.html Basic example of publishing a message to a subject. Requires a running NATS server and the NATS Java client library. ```java Connection nc = Nats.connect("nats://localhost:4222"); nc.publish(subject, message.getBytes(StandardCharsets.UTF_8)); ``` -------------------------------- ### Create a Manual Pull Subscription Source: https://github.com/nats-io/nats.java/blob/main/README.md This snippet shows how to create a manual pull subscription with optional durable naming. This is the initial setup for pull-based message consumption. ```java PullSubscribeOptions pullOptions = PullSubscribeOptions.builder() .durable("durable-name-is-optional") .build(); JetStreamSubscription sub = js.subscribe("subject", pullOptions); ``` -------------------------------- ### Subscribe to a Subject with NATS Java Source: https://github.com/nats-io/nats.java/blob/main/src/main/javadoc/overview.html Basic example of subscribing to a subject and receiving a message with a timeout. Requires a running NATS server and the NATS Java client library. ```java Connection nc = Nats.connect("nats://localhost:4222"); Subscription sub = nc.subscribe(subject); Message msg = sub.nextMessage(Duration.ofSeconds(1)); ``` -------------------------------- ### Make a Request and Wait for Reply Source: https://github.com/nats-io/nats.java/blob/main/README.md Send a request message to a subject and asynchronously wait for a reply using a Future. The reply is obtained by calling get() on the Future. ```java Future incoming = nc.request("subject", "hello world".getBytes(StandardCharsets.UTF_8)); Message msg = incoming.get(500, TimeUnit.MILLISECONDS); String response = new String(msg.getData(), StandardCharsets.UTF_8); ``` -------------------------------- ### Advanced Message Handling with Dispatchers in NATS Java Source: https://github.com/nats-io/nats.java/blob/main/src/main/javadoc/overview.html Example of using a Dispatcher for asynchronous message handling. Messages are processed in a separate thread upon arrival. Requires a running NATS server and the NATS Java client library. ```java Connection nc = Nats.connect("nats://localhost:4222"); Dispatcher d = nc.createDispatcher((msg) -> { System.out.printf("Received message \"%s\" on subject \"%s\"\n", new String(msg.getData(), StandardCharsets.UTF_8), msg.getSubject()); }); d.subscribe(subject); ``` -------------------------------- ### Get Consumer Info Source: https://github.com/nats-io/nats.java/blob/main/README.md Retrieves information about a specific consumer within a stream. This method can be resource-intensive on the server, especially with a large number of consumers. ```java ConsumerInfo getConsumerInfo(String streamName, String consumerName) throws IOException, JetStreamApiException; ``` -------------------------------- ### Run with TLS System Properties Source: https://github.com/nats-io/nats.java/blob/main/examples/src/main/java/io/nats/examples/README.md Configure SSL keystore and truststore via system properties for secure connections. ```bash java -Djavax.net.ssl.keyStore=src/test/resources/keystore.jks -Djavax.net.ssl.keyStorePassword=password -Djavax.net.ssl.trustStore=src/test/resources/truststore.jks -Djavax.net.ssl.trustStorePassword=password io.nats.examples.NatsPub tls://localhost:4443 test "hello world" ``` -------------------------------- ### Clone, Build, and Test NATS.java Source: https://github.com/nats-io/nats.java/blob/main/README.md Clone the repository, navigate to the directory, and build the project with tests using Gradle. ```bash #!/bin/bash git clone https://github.com/nats-io/nats.java cd nats.java ./gradlew clean build ``` -------------------------------- ### Run the compatibility CLI Source: https://github.com/nats-io/nats.java/blob/main/src/test/java/io/nats/compatibility/README.md Execute the CLI tool to run a specific test suite, such as the object-store suite. ```shell client-compatibility suite object-store ``` -------------------------------- ### Configure Multiple Servers for Connection Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure the Options builder to include multiple server URLs for initial connection. This is useful for connecting to NATS clusters. ```java String[] serverUrls = {"nats://serverOne:4222", "nats://serverTwo:4222"}; Options o = new Options.Builder().servers(serverUrls).build(); ``` -------------------------------- ### Configure server URL via command line Source: https://github.com/nats-io/nats.java/blob/main/src/test/java/io/nats/compatibility/README.md Pass a custom NATS server URL as a command line argument to the compatibility main class. ```shell > java -cp ... io.nats.compatibility.ClientCompatibilityMain nats://myhost:4333 ``` -------------------------------- ### GraalVM Initialization for NATS Client Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure GraalVM initialization parameters to ensure proper runtime initialization of NATS client classes. ```bash --initialize-at-run-time=java.security.SecureRandom --initialize-at-run-time=io.nats.client.support.RandomUtils --initialize-at-run-time=io.nats.client.NUID ``` -------------------------------- ### Publish with TLS using System Properties Source: https://github.com/nats-io/nats.java/blob/main/README.md Connect to a NATS server using TLS by setting Java system properties for keystore and truststore. This method works with or without client certificate verification. ```bash java -Djavax.net.ssl.keyStore=src/test/resources/keystore.jks -Djavax.net.ssl.keyStorePassword=password -Djavax.net.ssl.trustStore=src/test/resources/truststore.jks -Djavax.net.ssl.trustStorePassword=password io.nats.examples.NatsPub tls://localhost:4443 test "hello world" ``` -------------------------------- ### Generate Javadoc for NATS.java Source: https://github.com/nats-io/nats.java/blob/main/README.md Create Java documentation for the NATS.java project using the Gradle task 'javadoc'. The generated documentation will be in the 'build/docs' directory. ```bash #!/bin/bash ./gradlew javadoc ``` -------------------------------- ### Compile the NATS Java client Source: https://github.com/nats-io/nats.java/blob/main/src/test/java/io/nats/compatibility/README.md Use Gradle to clean and compile the test Java source files. ```shell > gradle clean compileTestJava ``` -------------------------------- ### Connect with Default Options Source: https://github.com/nats-io/nats.java/blob/main/README.md Connect to a local NATS server using default options. Supports reconnecting on initial connection failure. ```java Connection nc = Nats.connect(); // default options, reconnect on connect Connection nc = Nats.connectReconnectOnConnect(); ``` -------------------------------- ### Create TLS Keystore and Truststore Source: https://github.com/nats-io/nats.java/blob/main/README.md Commands to generate the necessary keystore.jks and truststore.jks files for TLS connections in NATS.java. These files are used to create SSLContexts. ```bash > cd src/test/resources > keytool -keystore truststore.jks -alias CARoot -import -file certs/ca.pem -storepass password -noprompt -storetype pkcs12 > cat certs/client-key.pem certs/client-cert.pem > combined.pem > openssl pkcs12 -export -in combined.pem -out cert.p12 > keytool -importkeystore -srckeystore cert.p12 -srcstoretype pkcs12 -deststoretype pkcs12 -destkeystore keystore.jks > keytool -keystore keystore.jks -alias CARoot -import -file certs/ca.pem -storepass password -noprompt > rm cert.p12 combined.pem ``` -------------------------------- ### Connect with Custom SSLContext Source: https://github.com/nats-io/nats.java/blob/main/README.md Build a custom SSLContext and use it to establish a NATS connection with specific security options. This allows for fine-grained control over TLS settings. ```java SSLContext ctx = createContext(); Options options = new Options.Builder().server(ts.getURI()).sslContext(ctx).build(); Connection nc = Nats.connect(options); ``` -------------------------------- ### Generic SSLContext Creation Properties Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure generic SSLContext creation using properties for the NATS client. ```properties # Generic SSLContext Creation io.nats.client.secure=true io.nats.client.opentls=true ``` -------------------------------- ### Compatibility engine ready output Source: https://github.com/nats-io/nats.java/blob/main/src/test/java/io/nats/compatibility/README.md The expected console output when the compatibility engine is initialized. ```text [main@473171716] Ready ``` -------------------------------- ### Bind to an Existing Consumer (Short Form) Source: https://github.com/nats-io/nats.java/blob/main/README.md This demonstrates the short form of binding a pull subscription to an existing consumer. It requires the stream and durable name. ```java PullSubscribeOptions pullOptions = PullSubscribeOptions.bind("stream", "durable-name"); JetStreamSubscription sub = js.subscribe(null, pullOptions); ``` -------------------------------- ### Gradle Repositories for Latest Versions Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure repositories in build.gradle to access the latest NATS client versions before they propagate to Maven Central. ```groovy repositories { mavenCentral() maven { url "https://repo1.maven.org/maven2/" } } ``` -------------------------------- ### Provide Custom SSLContext Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure NATS client options by directly providing a custom SSLContext. ```java // Provide the SSLContext public Builder sslContext(SSLContext ctx) ``` -------------------------------- ### Build NATS.java Without Tests Source: https://github.com/nats-io/nats.java/blob/main/README.md Build the NATS.java project using Gradle, excluding test execution. ```bash #!/bin/bash ./gradlew clean build -x test ``` -------------------------------- ### Custom SSLContext Creation Properties in Properties File Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure custom SSLContext creation properties using a properties file for the NATS client. ```properties # Custom SSLContext Creation Properties io.nats.client.keyStore=path/to/keystore.jks io.nats.client.keyStorePassword=kspassword io.nats.client.trustStore=path/to/truststore.jks io.nats.client.trustStorePassword=tspassword io.nats.client.tls.algorithm=SunX509 ``` -------------------------------- ### Run Unverified TLS Client Source: https://github.com/nats-io/nats.java/blob/main/examples/src/main/java/io/nats/examples/README.md Execute a NATS subscriber using the opentls protocol for unverified connections. ```bash java -cp build/libs/java-nats-{major.minor.patch}-SNAPSHOT-uber.jar io.nats.examples.NatsSub opentls://localhost:4443 test 3 ``` -------------------------------- ### Generic SSLContext Creation Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure NATS client options for generic SSLContext creation. ```java // Generic SSLContext Creation public Builder secure() public Builder opentls() ``` -------------------------------- ### Build NATS.java Jar Source: https://github.com/nats-io/nats.java/blob/main/README.md Generate a JAR file for the NATS.java library using Gradle. The output JAR will be located in the 'build/libs' directory. ```bash #!/bin/bash ./gradlew jar ``` -------------------------------- ### Custom SSLContext Creation Properties Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure NATS client options with custom properties for SSLContext creation, including keystore, truststore, and TLS algorithm. ```java // Custom SSLContext Creation Properties public Builder keystore(String keystore) public Builder keystorePassword(char[] keystorePassword) public Builder truststore(String truststore) public Builder truststorePassword(char[] truststorePassword) public Builder tlsAlgorithm(String tlsAlgorithm) ``` -------------------------------- ### Set Arguments in IDE Source: https://github.com/nats-io/nats.java/blob/main/examples/src/main/java/io/nats/examples/README.md Hardcode arguments in the IDE runner to simulate command line input. ```java args = "-arg1 myArg1 -arg2 myArg2".split(" "); args = new String[] {"-arg1", "myArg1", "-arg2", "myArg2"}; ``` -------------------------------- ### Subscribe with OpenTLS Protocol Source: https://github.com/nats-io/nats.java/blob/main/README.md Connect to a NATS server using the opentls:// protocol, which trusts all server certificates but provides no client certificates. This requires client verification to be off. ```bash java io.nats.examples.NatsSub opentls://localhost:4443 test 3 ``` -------------------------------- ### Connect with Custom Options Source: https://github.com/nats-io/nats.java/blob/main/README.md Connect to NATS servers using a custom Options object, allowing for specific configurations like multiple servers and reconnect attempts. Supports reconnecting on initial connection failure. ```java Options o = new Options.Builder().server("nats://serverone:4222").server("nats://servertwo:4222").maxReconnects(-1).build(); // custom options Connection nc = Nats.connect(o); // custom options, reconnect on connect Connection nc = Nats.connectReconnectOnConnect(o); ``` -------------------------------- ### Connect Asynchronously Source: https://github.com/nats-io/nats.java/blob/main/README.md Connect to a NATS server asynchronously. Requires a connection listener to be notified upon successful connection. Uses default URL and a provided handler. ```java Options options = new Options.Builder().server(Options.DEFAULT_URL).connectionListener(handler).build(); Nats.connectAsynchronously(options, true); ``` -------------------------------- ### Maven Repository for Latest Versions Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure repositories in pom.xml to access the latest NATS client versions before they propagate to Maven Central. ```xml sonatype releases https://repo1.maven.org/maven2/ true ``` -------------------------------- ### Manual Pull with Batch Size and Next Message Source: https://github.com/nats-io/nats.java/blob/main/README.md This demonstrates a raw pull request specifying a batch size, followed by fetching the next available message. It requires manual tracking of the batch to avoid errors like 'Exceeded MaxWaiting'. ```java sub.pull(100); ... Message m = sub.nextMessage(Duration.ofSeconds(1)); ``` -------------------------------- ### Bind to an Existing Consumer (Long Form) Source: https://github.com/nats-io/nats.java/blob/main/README.md This shows the long form of binding a pull subscription, using a builder pattern for more explicit configuration. It's useful for setting bind to true. ```java PullSubscribeOptions pullOptions = PullSubscribeOptions.builder() .stream("stream") .durable("durable-name") .bind(true) .build(); ``` -------------------------------- ### Publish with Options and Expectations Source: https://github.com/nats-io/nats.java/blob/main/README.md Publishes messages with specific options, including expected stream, message ID, and sequence number. The PublishOptions builder can be reused after clearing expectations. ```java PublishOptions.Builder pubOptsBuilder = PublishOptions.builder() .expectedStream("TEST") .messageId("mid1"); PublishAck pa = js.publish("foo", null, pubOptsBuilder.build()); pubOptsBuilder.clearExpected() .setExpectedLastMsgId("mid1") .setExpectedLastSequence(1) .messageId("mid2"); pa = js.publish("foo", null, pubOptsBuilder.build()); ``` -------------------------------- ### Connect with Single or Multiple URLs Source: https://github.com/nats-io/nats.java/blob/main/README.md Connect to one or more NATS servers using specified URLs. Supports reconnecting on initial connection failure. ```java // single URL, all other default options Connection nc = Nats.connect("nats://myhost:4222"); // comma-separated list of URLs, all other default options Connection nc = Nats.connect("nats://myhost:4222,nats://myhost:4223"); // single URL, all other default options, reconnect on connect Connection nc = Nats.connectReconnectOnConnect("nats://myhost:4222"); // comma-separated list of URLs, all other default options, reconnect on connect Connection nc = Nats.connectReconnectOnConnect("nats://myhost:4222,nats://myhost:4223"); ``` -------------------------------- ### Set Credential Path Directly Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure NATS client options by directly providing the path to the credentials file, allowing the client to create the AuthHandler automatically. ```java Options options = new Options.Builder() .credentialPath("path/to/my.creds") .build(); ``` -------------------------------- ### Set Credential Path in Properties File Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure the NATS client's credential path using a properties file. ```properties io.nats.client.credential.path=path/to/my.creds ``` -------------------------------- ### Message Acknowledgement Methods Source: https://github.com/nats-io/nats.java/blob/main/README.md Demonstrates the various methods available on a Message object for acknowledging or managing message delivery. ```java Message.ack(); Message.ackSync(Duration); Message.nak(); Message.term(); Message.inProgress(); ``` -------------------------------- ### Fetch Messages in a Batch Source: https://github.com/nats-io/nats.java/blob/main/README.md This snippet illustrates fetching a specified number of messages with a timeout. Messages are processed in a loop, and acknowledged individually. Be mindful of ack wait timers to avoid redeliveries. ```java List message = sub.fetch(100, Duration.ofSeconds(1)); for (Message m : messages) { // process message m.ack(); } ``` -------------------------------- ### Create JetStream Context Source: https://github.com/nats-io/nats.java/blob/main/README.md Obtain a JetStream context from an existing NATS connection to interact with JetStream features. Default options are usually sufficient. ```java JetStream js = nc.jetStream(); ``` -------------------------------- ### NATS Java Client Layering Diagram Source: https://github.com/nats-io/nats.java/blob/main/README.md Illustrates the relationship between application code, Orbit artifacts, the nats.java core client, and nats-server. Orbit artifacts use the core client, which in turn communicates with nats-server. ```text ┌──────────────────────────────────────────────────────┐ │ Application code │ └──────────────┬───────────────────────────┬───────────┘ │ │ ▼ ▼ ┌───────────────────┐ ┌───────────────────┐ │ Orbit artifacts │ uses │ nats.java (core) │ │ (opinionated, │──────▶│ (parity, stable, │ │ per-art semver) │ │ protocol-level) │ └───────────────────┘ └─────────┬─────────┘ │ ▼ ┌─────────────┐ │ nats-server │ └─────────────┘ ``` -------------------------------- ### Synchronous Publish Source: https://github.com/nats-io/nats.java/blob/main/README.md Publishes a single NATS message synchronously. An exception is thrown on failure, otherwise a PublishAck is returned. ```java // create a typical NATS message Message msg = NatsMessage.builder() .subject("foo") .data("hello", StandardCharsets.UTF_8) .build(); PublishAck pa = js.publish(msg); ``` -------------------------------- ### Run Tests and Generate Coverage Report Source: https://github.com/nats-io/nats.java/blob/main/README.md Execute tests for the NATS.java project and generate a JaCoCo test coverage report. The report will be available in 'build/reports/jacoco'. ```bash #!/bin/bash ./gradlew test jacocoTestReport ``` -------------------------------- ### Publish Message with Subject, ReplyTo, and Body Source: https://github.com/nats-io/nats.java/blob/main/README.md Publish a message to a specified subject, including a reply-to subject for responses, with a byte array body. ```java nc.publish("subject", "replyto", "hello world".getBytes(StandardCharsets.UTF_8)); ``` -------------------------------- ### Handle Response with Description and Extra Error Code Source: https://github.com/nats-io/nats.java/blob/main/src/test/resources/data/ErrorResponses.json.txt Use this when the response includes a description and an additional specific error code, but no standard error code. ```json { "type": "no-code_desc_err_response", "error": { "description": "the description", "err_code": 12345 } } ``` -------------------------------- ### Handle Non-Zero Error Code with Description Source: https://github.com/nats-io/nats.java/blob/main/src/test/resources/data/ErrorResponses.json.txt Use this when the response indicates an error with a specific non-zero code and a descriptive message. ```json { "type": "code_and_desc_response", "error": { "code": 500, "description": "the description" } } ``` -------------------------------- ### Handle Zero Error Code with Description Source: https://github.com/nats-io/nats.java/blob/main/src/test/resources/data/ErrorResponses.json.txt Use this when the response indicates an error with a zero code and a descriptive message. This might represent a specific type of non-critical error or a default state. ```json { "type": "zero_and_desc_response", "error": { "code": 0, "description": "the description" } } ``` -------------------------------- ### Gradle Dependency for NATS Client Source: https://github.com/nats-io/nats.java/blob/main/README.md Add the NATS client as a standard implementation dependency in your build.gradle file. ```groovy dependencies { implementation 'io.nats:jnats:2.25.3' } ``` -------------------------------- ### Enable Fast Fallback for Connections Source: https://github.com/nats-io/nats.java/blob/main/README.md Enable the fast fallback algorithm in NATS client options to improve connection speed and reliability for hostnames resolving to multiple IP addresses. ```java Options options = new Options.Builder() .enableFastFallback() .build(); ``` -------------------------------- ### Enable Advanced Request Behavior Source: https://github.com/nats-io/nats.java/blob/main/README.md Enable the advanced request behavior option when building NATS connection options. This allows for more detailed failure reasons. ```java Options options = Options.builder() .server("nats://localhost:4222") .advancedRequestBehavior() .build(); ``` -------------------------------- ### Connect with Authentication Handler Source: https://github.com/nats-io/nats.java/blob/main/README.md Connect to NATS servers using an authentication handler, typically for credentials. Supports various URL configurations and reconnect options. ```java AuthHandler authHandler = Nats.credentials(System.getenv("NATS_CREDS")); // single URL, all other default options Connection nc = Nats.connect("nats://myhost:4222", authHandler); // comma-separated list of URLs, all other default options Connection nc = Nats.connect("nats://myhost:4222,nats://myhost:4223", authHandler); // single URL, all other default options, reconnect on connect Connection nc = Nats.connectReconnectOnConnect("nats://myhost:4222", authHandler); // comma-separated list of URLs, all other default options, reconnect on connect Connection nc = Nats.connectReconnectOnConnect("nats://myhost:4222,nats://myhost:4223", authHandler); ``` -------------------------------- ### Handle Response with Description Only Source: https://github.com/nats-io/nats.java/blob/main/src/test/resources/data/ErrorResponses.json.txt Use this when the response indicates an error with a descriptive message but no specific error code is provided. ```json { "type": "no_code_response", "error": { "description": "no code" } } ``` -------------------------------- ### Subscribe with Filter Subject Source: https://github.com/nats-io/nats.java/blob/main/README.md Subscribe using PushSubscribeOptions with a ConsumerConfiguration that specifies a filter subject. The subscribe subject can be null in this case. ```java PushSubscribeOptions pso = ConsumerConfiguration.builder().filterSubject("my.subject").buildPushSubscribeOptions(); js.subscribe(null, pso); ``` -------------------------------- ### Gradle Dependency for Snapshot Versions Source: https://github.com/nats-io/nats.java/blob/main/README.md Include the snapshot repository and dependency in build.gradle to use NATS client snapshot versions. ```groovy repositories { mavenCentral() maven { url "https://central.sonatype.com/repository/maven-snapshots" } } dependencies { implementation 'io.nats:jnats:2.25.4-SNAPSHOT' } ``` -------------------------------- ### Maven Dependency for NATS Client Source: https://github.com/nats-io/nats.java/blob/main/README.md Include the NATS client as a dependency in your pom.xml file. ```xml io.nats jnats 2.25.3 ``` -------------------------------- ### NATS.java Options Builder 'Last-One Wins' Behavior Source: https://github.com/nats-io/nats.java/blob/main/README.md Illustrates how the Options builder prioritizes the last set value for a given property when both properties and code configurations are used. This applies to each property individually. ```java props.setProperty(Options.PROP_MAX_MESSAGES_IN_OUTGOING_QUEUE, "7000"); o = new Options.Builder() .properties(props) .maxMessagesInOutgoingQueue(6000) .build(); assertEquals(6000, o.getMaxMessagesInOutgoingQueue()); o = new Options.Builder() .maxMessagesInOutgoingQueue(6000) .properties(props) .build(); assertEquals(7000, o.getMaxMessagesInOutgoingQueue()); o = new Options.Builder() .maxMessagesInOutgoingQueue(6000) .maxMessagesInOutgoingQueue(8000) .build(); assertEquals(8000, o.getMaxMessagesInOutgoingQueue()); ``` -------------------------------- ### Asynchronous Push Subscription with Handler Source: https://github.com/nats-io/nats.java/blob/main/README.md Subscribe to a subject asynchronously using a Dispatcher and MessageHandler. Configure durable options and auto-acknowledgement. ```java Dispatcher disp = ...; MessageHandler handler = (msg) -> { // Process the message. // Ack the message depending on the ack model }; PushSubscribeOptions so = PushSubscribeOptions.builder() .durable("optional-durable-name") .build(); boolean autoAck = ... js.subscribe("my-subject", disp, handler, autoAck); ``` -------------------------------- ### Iterate Over Messages Source: https://github.com/nats-io/nats.java/blob/main/README.md This shows how to obtain an iterator for messages, allowing for immediate processing as messages become available. This method is generally preferred over fetch for efficiency and reduced ack wait issues. ```java Iterator iter = sub.iterate(100, Duration.ofSeconds(1)); while (iter.hasNext()) { Message m = iter.next(); // process message m.ack(); } ``` -------------------------------- ### Publish Message with Subject and Body Source: https://github.com/nats-io/nats.java/blob/main/README.md Publish a message to a specified subject with a given byte array body using the NATS client. ```java nc.publish("subject", "hello world".getBytes(StandardCharsets.UTF_8)); ``` -------------------------------- ### Synchronous Consuming with Push Subscription Source: https://github.com/nats-io/nats.java/blob/main/README.md Subscribe synchronously to a subject and then retrieve messages using nextMessage. Includes flushing the connection and setting a timeout. ```java PushSubscribeOptions so = PushSubscribeOptions.builder() .durable("optional-durable-name") .build(); // Subscribe synchronously, then just wait for messages. JetStreamSubscription sub = js.subscribe("subject", so); nc.flush(Duration.ofSeconds(5)); Message msg = sub.nextMessage(Duration.ofSeconds(1)); ``` -------------------------------- ### Set AuthHandler with JWT Credentials Source: https://github.com/nats-io/nats.java/blob/main/README.md Manually create and set an AuthHandler using JWT credentials in NATS client options. ```java AuthHandler ah = Nats.credentials("path/to/my.creds"); Options options = new Options.Builder() .authHandler(ah) .build(); ``` -------------------------------- ### Maven Dependency for Snapshot Versions Source: https://github.com/nats-io/nats.java/blob/main/README.md Enable snapshots in Maven repositories and update the dependency in pom.xml to use NATS client snapshot versions. ```xml sonatype snapshots https://central.sonatype.com/repository/maven-snapshots true io.nats jnats 2.25.4-SNAPSHOT ``` -------------------------------- ### Force Reconnect API Source: https://github.com/nats-io/nats.java/blob/main/README.md Initiate an immediate reconnection process using the `forceReconnect` API on the `Connection` interface. This can be called with or without options. ```java void forceReconnect() throws IOException, InterruptedException; void forceReconnect(ForceReconnectOptions options) throws IOException, InterruptedException; ``` -------------------------------- ### Enable OCSP Stapling in Java JVM Source: https://github.com/nats-io/nats.java/blob/main/README.md Set these system properties to enable the Java Virtual Machine to automatically check for OCSP stapling during TLS connections. This affects the entire JVM. ```java System.setProperty("jdk.tls.client.enableStatusRequestExtension", "true"); System.setProperty("com.sun.net.ssl.checkRevocation", "true"); ``` -------------------------------- ### Handle Response with Multiple Error Fields Source: https://github.com/nats-io/nats.java/blob/main/src/test/resources/data/ErrorResponses.json.txt Use this when the response includes both a standard error code and description, along with an additional specific error code. ```json { "type": "code_desc_err_response", "error": { "code": 500, "description": "the description", "err_code": 12345 } } ``` -------------------------------- ### Dispatcher Subscription with Shared Callback Source: https://github.com/nats-io/nats.java/blob/main/README.md Use a Dispatcher to manage multiple subjects with a single background thread and a shared callback function for message handling. ```java Dispatcher d = nc.createDispatcher((msg) -> { String response = new String(msg.getData(), StandardCharsets.UTF_8); ... }); d.subscribe("subject"); ``` -------------------------------- ### Handle Non-Zero Error Code Only Source: https://github.com/nats-io/nats.java/blob/main/src/test/resources/data/ErrorResponses.json.txt Use this when the response indicates an error with a specific non-zero code but no descriptive message is provided. ```json { "type": "non_zero_code_only_response", "error": { "code": 500 } } ``` -------------------------------- ### Handle Empty Error Object Source: https://github.com/nats-io/nats.java/blob/main/src/test/resources/data/ErrorResponses.json.txt Use this when the response contains an error object that is empty, indicating no specific error details. ```json { "type": "empty_response", "error": {} } ``` -------------------------------- ### Asynchronous Publish Source: https://github.com/nats-io/nats.java/blob/main/README.md Publishes multiple NATS messages asynchronously, collecting PublishAck futures. Process the futures to handle acknowledgements or errors. ```java List> futures = new ArrayList<>(); for (int x = 1; x < roundCount; x++) { // create a typical NATS message Message msg = NatsMessage.builder() .subject("foo") .data("hello", StandardCharsets.UTF_8) .build(); // Publish a message futures.add(js.publishAsync(msg)); } for (CompletableFuture future : futures) { ... process the futures } ``` -------------------------------- ### Consumer Configuration with Multiple Filter Subjects Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure a JetStream consumer to accept messages from multiple filter subjects using the ConsumerConfiguration builder. ```java ConsumerConfiguration cc = ConsumerConfiguration.builder() ... .filterSubjects("subject1", "subject2") .build(); ``` -------------------------------- ### Configure Subject Validation via Properties Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure subject validation using properties. 'noSubjectValidation=true' disables validation, while 'strictSubjectValidation=true' enables strict validation. ```properties noSubjectValidation=true ``` ```properties strictSubjectValidation=true ``` -------------------------------- ### Dispatcher Subscription with Individual Callback Source: https://github.com/nats-io/nats.java/blob/main/README.md Assign a specific callback function to a subscription managed by a Dispatcher. Unsubscribe after a specified number of messages. ```java Dispatcher d = nc.createDispatcher((msg) -> {}); Subscription s = d.subscribe("some.subject", (msg) -> { String response = new String(msg.getData(), StandardCharsets.UTF_8); System.out.println("Message received (up to 100 times): " + response); }); d.unsubscribe(s, 100); ``` -------------------------------- ### Handle Response Without Type Field Source: https://github.com/nats-io/nats.java/blob/main/src/test/resources/data/ErrorResponses.json.txt Use this when the response has an error code and description but is missing the 'type' field. This might indicate a malformed or unexpected response structure. ```json { "error": { "code": 500, "description": "didnt have type" } } ``` -------------------------------- ### No Wait Pull with Batch Size and Next Message Source: https://github.com/nats-io/nats.java/blob/main/README.md This snippet shows a 'no wait' pull request with a batch size. It fetches available messages immediately up to the batch size, without waiting for the full batch to be ready. ```java sub.pullNoWait(100); ... Message m = sub.nextMessage(Duration.ofSeconds(1)); ``` -------------------------------- ### Handle Core Request Failure Message Source: https://github.com/nats-io/nats.java/blob/main/README.md Inspect the returned `Message` for core NATS requests when advanced request behavior is enabled. It may be a `RequestFailureMessage` providing failure details. ```java Message m = nc.request("subject", data, Duration.ofSeconds(2)); if (m instanceof RequestFailureMessage) { RequestFailureMessage rfm = (RequestFailureMessage)m; log.warn("request failed: {} (status={})", rfm.getReason(), rfm.getConnectionStatus()); } ``` -------------------------------- ### Handle Response Without Error Object Source: https://github.com/nats-io/nats.java/blob/main/src/test/resources/data/ErrorResponses.json.txt Use this when the response does not contain an 'error' field, indicating a successful operation or a response type that does not include error details. ```json { "type": "not_error_response" } ``` -------------------------------- ### Enable Strict Subject Validation Source: https://github.com/nats-io/nats.java/blob/main/README.md Use this builder method to enforce strict subject validation. This checks for improper segment formation and wildcard usage. ```java public Builder strictSubjectValidation(); ``` -------------------------------- ### Enable No Subject Validation Source: https://github.com/nats-io/nats.java/blob/main/README.md Use this builder method to disable subject validation. This is useful when you want to control subjects yourself. ```java public Builder noSubjectValidation(); ``` -------------------------------- ### Synchronous Subscription Source: https://github.com/nats-io/nats.java/blob/main/README.md Use for applications that manually poll for messages. The call blocks until a message is received or the timeout occurs. ```java Subscription sub = nc.subscribe("subject"); Message msg = sub.nextMessage(Duration.ofMillis(500)); String response = new String(msg.getData(), StandardCharsets.UTF_8); ``` -------------------------------- ### NATS JetStream Pull Subscription with Expiration Source: https://github.com/nats-io/nats.java/blob/main/README.md Configure pull subscriptions to expire after a specified duration and retrieve messages within a timeout. Ensure the client's nextMessage timeout is longer than the server's expiration time. ```java sub.pullExpiresIn(100, Duration.ofSeconds(3)); ... Message m = sub.nextMessage(Duration.ofSeconds(4)); ```