Java client for NATS

Overview

NATS

NATS - Java Client

A Java client for the NATS messaging system.

License Apache 2 Build Status Coverage Status Maven Central Javadoc

A Note on Versions

This is version 2.x of the java-nats library. This version is a ground up rewrite of the original library. Part of the goal of this re-write was to address the excessive use of threads, we created a Dispatcher construct to allow applications to control thread creation more intentionally. This version also removes all non-JDK runtime dependencies.

The API is simple to use and highly performant.

Version 2+ uses a simplified versioning scheme. Any issues will be fixed in the incremental version number. As a major release, the major version has been updated to 2 to allow clients to limit there use of this new API. With the addition of drain() we updated to 2.1, NKey support moved us to 2.2.

The NATS server renamed itself from gnatsd to nats-server around 2.4.4. This and other files try to use the new names, but some underlying code may change over several versions. If you are building yourself, please keep an eye out for issues and report them.

Version 2.5.0 adds some back pressure to publish calls to alleviate issues when there is a slow network. This may alter performance characteristics of publishing apps, although the total performance is equivalent.

Previous versions are still available in the repo.

SSL/TLS Performance

After recent tests we realized that TLS performance is lower than we would like. After researching the problem and possible solutions we came to a few conclusions:

  • TLS performance for the native JDK has not be historically great
  • TLS performance is better in JDK12 than JDK8
  • A small fix to the library in 2.5.1 allows the use of https://github.com/google/conscrypt and https://github.com/wildfly/wildfly-openssl, conscrypt provides the best performance in our tests
  • TLS still comes at a price (1gb/s vs 4gb/s in some tests), but using the JNI libraries can result in a 10x boost in our testing
  • If TLS performance is reasonable for your application we recommend using the j2se implementation for simplicity

To use conscrypt or wildfly, you will need to add the appropriate jars to your class path and create an SSL context manually. This context can be passed to the Options used when creating a connection. The NATSAutoBench example provides a conscrypt flag which can be used to try out the library, manually including the jar is required.

UTF-8 Subjects

The client protocol spec doesn't explicitly state the encoding on subjects. Some clients use ASCII and some use UTF-8 which matches ASCII for a-Z and 0-9. Until 2.1.2 the 2.0+ version of the Java client used ASCII for performance reasons. As of 2.1.2 you can choose to support UTF-8 subjects via the Options. Keep in mind that there is a small performance penalty for UTF-8 encoding and decoding in benchmarks, but depending on your application this cost may be negligible. Also, keep in mind that not all clients support UTF-8 and test accordingly.

NKey-based Challenge Response Authentication

The NATS server is adding support for a challenge response authentication scheme based on NKeys. Version 2.2.0 of the Java client supports this scheme via an AuthHandler interface. Version 2.3.0 replaced several NKey methods that used strings with methods using char[] to improve security.

Installation

The java-nats client is provided in a single jar file, with a single external dependency for the encryption in NKey support. See Building From Source for details on building the library.

Downloading the Jar

You can download the latest jar at https://search.maven.org/remotecontent?filepath=io/nats/jnats/2.8.0/jnats-2.8.0.jar.

The examples are available at https://search.maven.org/remotecontent?filepath=io/nats/jnats/2.8.0/jnats-2.8.0-examples.jar.

To use NKeys, you will need the ed25519 library, which can be downloaded at https://repo1.maven.org/maven2/net/i2p/crypto/eddsa/0.3.0/eddsa-0.3.0.jar.

Using Gradle

The NATS client is available in the Maven central repository, and can be imported as a standard dependency in your build.gradle file:

dependencies {
    implementation 'io.nats:jnats:2.8.0'
}

If you need the latest and greatest before Maven central updates, you can use:

repositories {
    jcenter()
    maven {
        url "https://oss.sonatype.org/content/repositories/releases"
    }
    maven {
        url "https://oss.sonatype.org/content/repositories/snapshots"
    }
}

Using Maven

The NATS client is available on the Maven central repository, and can be imported as a normal dependency in your pom.xml file:

<dependency>
    <groupId>io.nats</groupId>
    <artifactId>jnats</artifactId>
    <version>2.8.0</version>
</dependency>

If you need the absolute latest, before it propagates to maven central, you can use the repository:

<repositories>
    <repository>
        <id>latest-repo</id>
        <url>https://oss.sonatype.org/content/repositories/releases</url>
        <releases><enabled>true</enabled></releases>
        <snapshots><enabled>false</enabled></snapshots>
    </repository>
</repositories>

If you are using the 1.x version of java-nats and don't want to upgrade to 2.0.0 please use ranges in your POM file, java-nats-streaming 1.x is using [1.1, 1.9.9) for this.

Basic Usage

Sending and receiving with NATS is as simple as connecting to the nats-server and publishing or subscribing for messages. A number of examples are provided in this repo as described in examples.md.

Connecting

There are four different ways to connect using the Java library:

  1. Connect to a local server on the default port:

    Connection nc = Nats.connect();
  2. Connect to one or more servers using a URL:

    //single URL
    Connection nc = Nats.connect("nats://myhost:4222");
    
    //comma-separated list of URLs
    Connection nc = Nats.connect("nats://myhost:4222,nats://myhost:4223");
  3. Connect to one or more servers with a custom configuration:

    Options o = new Options.Builder().server("nats://serverone:4222").server("nats://servertwo:4222").maxReconnects(-1).build();
    Connection nc = Nats.connect(o);

    See the javadoc for a complete list of configuration options.

  4. Connect asynchronously, this requires a callback to tell the application when the client is connected:

    Options options = new Options.Builder().server(Options.DEFAULT_URL).connectionListener(handler).build();
    Nats.connectAsynchronously(options, true);

    This feature is experimental, please let us know if you like it.

  5. Connect with authentication handler:

    AuthHandler authHandler = Nats.credentials(System.getenv("NATS_CREDS")
    Connection nc = Nats.connect("nats://myhost:4222", authHandler);

Publishing

Once connected, publishing is accomplished via one of three methods:

  1. With a subject and message body:

    nc.publish("subject", "hello world".getBytes(StandardCharsets.UTF_8));
  2. With a subject and message body, as well as a subject for the receiver to reply to:

    nc.publish("subject", "replyto", "hello world".getBytes(StandardCharsets.UTF_8));
  3. As a request that expects a reply. This method uses a Future to allow the application code to wait for the response. Under the covers a request/reply pair is the same as a publish/subscribe only the library manages the subscription for you.

    Future<Message> 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);

All of these methods, as well as the incoming message code use byte arrays for maximum flexibility. Applications can send JSON, Strings, YAML, Protocol Buffers, or any other format through NATS to applications written in a wide range of languages.

Listening for Incoming Messages

The Java NATS library provides two mechanisms to listen for messages, three if you include the request/reply discussed above.

  1. Synchronous subscriptions where the application code manually asks for messages and blocks until they arrive. Each subscription is associated with a single subject, although that subject can be a wildcard.

    Subscription sub = nc.subscribe("subject");
    Message msg = sub.nextMessage(Duration.ofMillis(500));
    
    String response = new String(msg.getData(), StandardCharsets.UTF_8);
  2. A Dispatcher that will call application code in a background thread. Dispatchers can manage multiple subjects with a single thread and shared callback.

    Dispatcher d = nc.createDispatcher((msg) -> {
        String response = new String(msg.getData(), StandardCharsets.UTF_8);
        ...
    });
    
    d.subscribe("subject");

    A dispatcher can also accept individual callbacks for any given subscription.

    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);

Jetstream

Publishing and subscribing to Jetstream enabled servers is straightforward. A Jetstream enabled application will connect to a server, establish a Jetstream context, and then publish or subscribe. This can be mixed and matched with standard NATS subject, and JetStream subscribers, depending on configuration, receive messages from both streams and directly from other NATS producers.

The Jetstream Context

After establishing a connection as described above, create a Jetstream Context.

    JetStream js = nc.jetStream();

You can pass options to configure the Jetstream client, although the defaults should suffice for most users. See the JetStreamOptions class.

There is no limit to the number of contexts used, although normally one would only require a single context. Contexts may be prefixed to be used in conjunction with NATS authorization.

Publishing

To publish messages, use the JetStream.Publish(...) API. A stream must be established before publishing.

    // create a typical NATS message
    Message msg = NatsMessage.builder()
            .subject("foo")
            .data("hello", StandardCharsets.UTF_8)
            .build();

    PublishAck pa = js.publish(msg);

If there is a problem an exception will be thrown, and the message may not have been persisted. Otherwise, the stream name and sequence number is returned in the publish acknowledgement.

There are a variety of publish options that can be set when publishing. When duplicate checking has been enabled on the stream, a message ID should be set. One set of options are expectations. You can set a publish expectation such as a particular stream name, previous message ID, or previous sequence number. These are hints to the server that it should reject messages where these are not met, primarily for enforcing your ordering or ensuring messages are not stored on the wrong stream.

For example:

    PublishOptions opts = PublishOptions.builder().expectedStream("TEST").build();
    opts.setMessageId("mid1");
    js.publish("foo", null, opts);

    opts.setExpectedLastMsgId("mid1");
    opts.setMessageId("mid2");
    opts.setExpectedLastSequence(1);
    js.publish("foo", null, opts);

Subscribing

There are three methods of subscribing: synchronous, synchronous with poll, and asynchronous. With synchronous subscribers you must always acknowledge messages. Asynchronous subscribers auto acknowledge by default, although this can be disabled through the subscription options in case you are using a consumer ack mode of none or all in the consumer configuration.

These examples provide a durable so messages will be preserved across server restarts (when a stream is using file storage) and client disconnects. Any subscriber can be a queue subscriber to load balance.

Asynchronous:

    Dispatcher d;

    ...

    SubscribeOptions so = SubscribeOptions.builder().durable("durable-name").build();
    js.subscribe(exArgs.subject, d, (Message msg) -> {
        // Process the message.  There is no need to ack unless auto ack
        // was disabled in the options.
    }, so);

Synchronous:

    SubscribeOptions so = SubscribeOptions.builder().durable("sub-example").build();
    JetStreamSubscription sub = js.subscribe(exArgs.subject, so);
    Message msg = sub.nextMessage(Duration.ofHours(1));

    // process the message

    msg.ack();

Synchronous with poll:

A subscription can be set up to poll to request messages from a JetStream consumer, allowing for high performance while reducing impact to the server.

    SubscribeOptions so = SubscribeOptions.builder().poll(64).durable("sub-example").build();
    JetStreamSubscription sub = js.subscribe(exArgs.subject, so);
    while (true) {
        for (int i = 0; i < 64; i++) {
            Message msg = sub.nextMessage(Duration.ofMinutes(5));

            // process the message

            msg.ack();
        }
        // get the next batch of messages.
        sub.poll();
    }

If the consumer had an acknowledgement mode of "all", you could acknowledge only the last message to balance performance against the possibility of reprocessing a number of messages.

Message Acknowledgements

There are multiple types of acknowledgements in Jetstream:

  • Message.ack(): Acknowledges a message.
  • Message.ackSync(Duration): Acknowledges a message and waits for a confirmation. When used with deduplications this creates exactly once delivery guarantees (within the deduplication window). This may significantly impact performance of the system.
  • Message.nak(): A negative acknowledgment indicating processing failed and the message should be resent later.
  • Message.term(): Never send this message again, regardless of configuration.
  • Message.inProgress(): The message is being processed and reset the redelivery timer in the server. The message must be acknowledged later when processing is complete.

Note that exactly once delivery guarantee can be achieved by using a consumer with explicit ack mode attached to stream setup with a deduplication window and using the ackSync to acknowledge messages. The guarantee is only valid for the duration of the deduplication window.

Advanced Usage

TLS

NATS supports TLS 1.2. The server can be configured to verify client certificates or not. Depending on this setting the client has several options.

  1. The Java library allows the use of the tls:// protocol in its urls. This setting expects a default SSLContext to be set. You can set this default context using System properties, or in code. For example, you could run the publish example using:

    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"

    where the following properties are being set:

    -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

    This method can be used with or without client verification.

  2. During development, or behind a firewall where the client can trust the server, the library supports the opentls:// protocol which will use a special SSLContext that trusts all server certificates, but provides no client certificates.

    java io.nats.examples.NatsSub opentls://localhost:4443 test 3

    This method requires that client verification is off.

  3. Your code can build an SSLContext to work with or without client verification.

    SSLContext ctx = createContext();
    Options options = new Options.Builder().server(ts.getURI()).sslContext(ctx).build();
    Connection nc = Nats.connect(options);

If you want to try out these techniques, take a look at the examples.md for instructions.

Clusters & Reconnecting

The Java client will automatically reconnect if it loses its connection the nats-server. If given a single server, the client will keep trying that one. If given a list of servers, the client will rotate between them. When the nats servers are in a cluster, they will tell the client about the other servers, so that in the simplest case a client could connect to one server, learn about the cluster and reconnect to another server if its initial one goes down.

To tell the connection about multiple servers for the initial connection, use the servers() method on the options builder, or call server() multiple times.

String[] serverUrls = {"nats://serverOne:4222", "nats://serverTwo:4222"};
Options o = new Options.Builder().servers(serverUrls).build();

Reconnection behavior is controlled via a few options, see the javadoc for the Options.Builder class for specifics on reconnect limits, delays and buffers.

Benchmarking

The io.nats.examples package contains two benchmarking tools, modeled after tools in other NATS clients. Both examples run against an existing nats-server. The first called io.nats.examples.benchmark.NatsBench runs two simple tests, the first simply publishes messages, the second also receives messages. Tests are run with 1 thread/connection per publisher or subscriber. Running on an iMac (2017), with 4.2 GHz Intel Core i7 and 64GB of memory produced results like:

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

The second, called io.nats.examples.autobench.NatsAutoBench runs a series of tests with various message sizes. Running this test on the same iMac, resulted in:

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)

It is worth noting that in both cases memory was not a factor, the processor and OS were more of a consideration. To test this, take a look at the NatsBench results again. Those are run without any constraint on the Java heap and end up doubling the used memory. However, if we run the same test again with a constraint of 1Gb using -Xmx1g, the performance is comparable, differentiated primarily by "noise" that we can see between test runs with the same settings.

Starting benchmark(s) [msgs=5000000, msgsize=256, pubs=2, subs=2]
Current memory usage is 976.38 mb / 981.50 mb / 981.50 mb free/total/max
Use ctrl-C to cancel.

Pub Only stats: 10,123,382 msgs/sec ~ 2.41 gb/sec
 [ 1] 5,068,256 msgs/sec ~ 1.21 gb/sec (2500000 msgs)
 [ 2] 5,061,691 msgs/sec ~ 1.21 gb/sec (2500000 msgs)
  min 5,061,691 | avg 5,064,973 | max 5,068,256 | stddev 3,282.50 msgs

Pub/Sub stats: 3,563,770 msgs/sec ~ 870.06 mb/sec
 Pub stats: 1,188,261 msgs/sec ~ 290.10 mb/sec
  [ 1] 594,701 msgs/sec ~ 145.19 mb/sec (2500000 msgs)
  [ 2] 594,130 msgs/sec ~ 145.05 mb/sec (2500000 msgs)
   min 594,130 | avg 594,415 | max 594,701 | stddev 285.50 msgs
 Sub stats: 2,375,839 msgs/sec ~ 580.04 mb/sec
  [ 1] 1,187,919 msgs/sec ~ 290.02 mb/sec (5000000 msgs)
  [ 2] 1,187,920 msgs/sec ~ 290.02 mb/sec (5000000 msgs)
   min 1,187,919 | avg 1,187,919 | max 1,187,920 | stddev .71 msgs


Final memory usage is 317.62 mb / 960.50 mb / 960.50 mb free/total/max

Building From Source

The build depends on Gradle, and contains gradlew to simplify the process. After cloning, you can build the repository and run the tests with a single command:

> git clone https://github.com/nats-io/nats.java
> cd nats.java
> ./gradlew build

This will place the class files in a new build folder. To just build the jar:

> ./gradlew jar

The jar will be placed in build/libs.

You can also build the java doc, and the samples jar using:

> ./gradlew javadoc
> ./gradlew exampleJar

The java doc is located in build/docs and the example jar is in build/libs. Finally, to run the tests with the coverage report:

> ./gradlew test jacocoTestReport

which will create a folder called build/reports/jacoco containing the file index.html you can open and use to browse the coverage. Keep in mind we have focused on library test coverage, not coverage for the examples.

Many of the tests run nats-server on a custom port. If nats-server is in your path they should just work, but in cases where it is not, or an IDE running tests has issues with the path you can specify the nats-server location with the environment variable nats_-_server_path.

TLS Certs

The raw TLS test certs are in src/test/resources/certs and come from the nats.go repository. However, the java client also needs a keystore and truststore.jks files for creating a context. These can be created using:

> 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

License

Unless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.

You might also like...

EssentialClient is a client side mod originally forked from Carpet Client for 1.15.2 that implements new client side features

EssentialClient is a client side mod originally forked from Carpet Client for 1.15.2 that implements new client side features

EssentialClient EssentialClient is a client side only mod originally forked from Carpet Client for 1.15.2 that implements new client side features. Th

Jan 3, 2023

This is the src of Badlion client 3.0.0, The reason of this repo is badlion client's owner being p e d o

About Badlion Using Gradle instead of the shit mcp uwu Commands Run with random username gradle startGame Run with another username gradle startGame -

Dec 2, 2022

This is the src of Badlion client 3.0.0, The reason of this repo is badlion client's owner being p e d o

About Badlion Using Gradle instead of the shit mcp uwu Commands Run with random username gradle startGame Run with another username gradle startGame -

Dec 2, 2022

ZerotierFix - An unofficial Zerotier Android client patched from official client

ZerotierFix - An unofficial Zerotier Android client patched from official client

Zerotier Fix An unofficial Zerotier Android client patched from official client. Features Self-hosted Moon Support Add custom planet config via file a

Jan 8, 2023

Exeter client. A client created by Friendly, for Minecraft version 1.8

Exeter client. A client created by Friendly, for Minecraft version 1.8

Exeter client. A client created by Friendly, for Minecraft version 1.8. It has been released or leaked on that version.

Dec 31, 2022

Checkers game. Server and Client. Client's app handled in JavaFX. Play with radom player or against AI.

Checkers game. Server and Client. Client's app handled in JavaFX. Play with radom player or against AI.

Checkers-JavaFX-and-Sockets Checkers game. Server and Client. Client's app handled in JavaFX. Play with radom player or against AI. If you want to pla

Mar 30, 2022

The Lezard Client is a new, open-source, minecraft client for the newer versions of the game.

The Lezard Client is a new, open-source, minecraft client for the newer versions of the game.

The Lezard Client is a new, open-source, minecraft client for the newer versions of the game. It is oriented not for PvP, but for the Vanilla and the Survival experience. It is not a hack client for Minecraft and do not ask for it. 1 I hate hacked client and 2 it is not fun for other people. Also, I misspelled the word lizard in English and decided to leave it like that.

Jul 5, 2022

A modular and portable open source XMPP client library written in Java for Android and Java (SE) VMs

Smack About Smack is an open source, highly modular, easy to use, XMPP client library written in Java for Java SE compatible JVMs and Android. A pure

Dec 28, 2022

A high-level and lightweight HTTP client framework for Java. it makes sending HTTP requests in Java easier.

A high-level and lightweight HTTP client framework for Java. it makes sending HTTP requests in Java easier.

A high-level and lightweight HTTP client framework for Java. it makes sending HTTP requests in Java easier.

Jan 8, 2023

A blazingly small and sane redis java client

A blazingly small and sane redis java client

Jedis Jedis is a blazingly small and sane Redis java client. Jedis was conceived to be EASY to use. Jedis is fully compatible with redis 2.8.x, 3.x.x

Dec 31, 2022

Elasticsearch Java Rest Client.

JEST Jest is a Java HTTP Rest client for ElasticSearch. ElasticSearch is an Open Source (Apache 2), Distributed, RESTful, Search Engine built on top o

Jan 1, 2023

Java client library for the Square Connect v2 API

Square Connect Java SDK - RETIRED NOTICE: Square Connect Java SDK retired The Square Connect Java SDK is retired (EOL) as of 2019-12-17 and will no lo

Jan 26, 2022

Asynchronous Http and WebSocket Client library for Java

Async Http Client Follow @AsyncHttpClient on Twitter. The AsyncHttpClient (AHC) library allows Java applications to easily execute HTTP requests and a

Jan 8, 2023

Google HTTP Client Library for Java

Google HTTP Client Library for Java Description Written by Google, the Google HTTP Client Library for Java is a flexible, efficient, and powerful Java

Jan 4, 2023

Unirest in Java: Simplified, lightweight HTTP client library.

Unirest for Java Install With Maven: !-- Pull in as a traditional dependency -- dependency groupIdcom.konghq/groupId artifactIdunire

Jan 5, 2023

Java client for Consul HTTP API

consul-api Java client for Consul HTTP API (http://consul.io) Supports all API endpoints (http://www.consul.io/docs/agent/http.html), all consistency

Jan 6, 2023
Comments
  • Websocket Beta

    Websocket Beta

    From @brimworks :

    This is the simplest possible implementation of websockets with a net increase in code coverage.

    • No alterations to DataPort.
    • Two new options, one to support httpInterceptors and another to support proxy requests.
    • Websockets is supported via a new schema ("ws" or "wss").
    • Copy writer headers are at the top of every new file added.
    • All websocket implementation details are encapsulated by extending Socket and implementing WebSocket with a WebSocketInputStream and WebSocketOutputStream.

    Being critical of myself, these are the points that are lacking:

    • Proper websocket closure handshake is not implemented, close() simply forwards to the underlying socket.
    • The http interceptors don't allow filtering HTTP responses and are very primitive. They work for my use case, but not sure if it works for all use-cases.
    • The handling of upgradeToSecure is a little awkward since websockets is typically performed over a TLS channel and thus there is no need for double encryption. A better solution would involve delegating this to the DataPort... or more specifically, when the secure() option is set, we should NOT throw an error if "wss" transport is used.
    • Create URI for server now takes in an "is websocket" parameter, again this is a little awkward. A better solution would involve delegating this to the DataPort.
    • No support for Sec-WebSocket-Extensions: permessage-deflate (aka websocket level compression... which should really be combined with Nats-No-Masking: TRUE to really get the full benefits).
    • The implementation of websocket framing strikes a balance between TCP fragmentation and extra buffer copying by using a 1440 sized buffer used for the initial frame header + the first ~1438 bytes. The channel based implementation mitigates this fragmentation by using the GatheringByteChannel and passing in an array of ByteBuffers.

    For more information on websockets, I'd really recommend reading the RFC: https://datatracker.ietf.org/doc/html/rfc6455

    opened by scottf 0
  • Auth Required Parity Issue

    Auth Required Parity Issue

    This client checks the auth required flag and prohibits sending credentials when set. The go client does not do this.

    See: https://github.com/nats-io/nats-server/pull/3667

    opened by ColinSullivan1 0
  • Wrong Exception is thrown when publishing a JetStream message

    Wrong Exception is thrown when publishing a JetStream message

    Defect

    Make sure that these boxes are checked before submitting your issue -- thank you!

    • [ ] Included a [Minimal, Complete, and Verifiable example] (https://stackoverflow.com/help/mcve)

    Versions of io.nats:jnats and nats-server:

    io.nats:jnats: 2.16.1 nats-server: 2.8.4

    OS/Container environment:

    Client: Windows 10 Server: alpine docker image

    Steps or code to reproduce the issue:

    1. Start a nats-server with default configuration and no streams configured
    2. Publish a JetStream message
    natsConn.jetStream().publish("test", myMessageBytes)
    

    Expected result:

    The publish function throws a JetStreamApiException with the right error code.

    Actual result:

    The publish function throws an IOException https://github.com/nats-io/nats.java/blob/main/src/main/java/io/nats/client/impl/NatsJetStream.java#L153

    This makes it impossible to determine between JetStream errors and connection/communication errors.

    🎉 enhancement 
    opened by joschiwald 3
Releases(2.16.5)
  • 2.16.5(Nov 25, 2022)

    Core

    • increase default max (pending) messages, ability to set pending limits in subscribe options #799 @scottf
    • better setup of pending limits #804 @scottf
    • ignore auth required flag from server when building connection string #807 @scottf @ColinSullivan1

    Etc. Tests / Docs / Examples

    • Fix test only check mirror direct 2.9.0 and later #794 @scottf
    • Fixes typo in Readme #795 @aaabramov
    • Better dev version and autobench naming #798 @scottf
    • Change Temporary File Creation in unit test. #800 @JLLeitschuh
    • fixed test - name not necessary, better for regression #803 @scottf
    Source code(tar.gz)
    Source code(zip)
  • 2.16.4(Nov 8, 2022)

    Key Value (KV)

    • kv mirror support #789 @scottf

    JetStream

    • stream state lost #792 @scottf

    Core

    • Implement RTT #784 @scottf
    • get client inet address #791 @scottf

    Misc

    • Minor fix for README.md Jetstream example #790 @JonasPed
    Source code(tar.gz)
    Source code(zip)
  • 2.16.3(Oct 27, 2022)

  • 2.16.2(Oct 26, 2022)

    Core

    • reader HMSG protocol line length size was wrong #774 @scottf
    • Message sending optimization #776 @scottf @MauriceVanVeen

    Misc

    • Fix Get Streams Doc #771 @scottf
    • PubWithHeadersBenchmark #772 @scottf
    Source code(tar.gz)
    Source code(zip)
  • 2.16.1(Oct 8, 2022)

    Core

    • Fix - Ensure resizing of the sendBuffer #746 @MauriceVanVeen
    • Enhancement - Additional API to clear last error from Nats server #750 @Ryner51
    • Sync NatsMessage.getSizeInBytes() with usage in NatsConnectionWriter #756 @MauriceVanVeen

    JetStream

    • discard_new_per_subject #755 @scottf
    • streams / names with subject filtering, info pagination #759 @scottf
    • ordered consumer config setting changes #762 @scottf
    • Ordered Consumer Heartbeat Handling #766 @scottf

    KV or OS

    • object store tuning #731 @scottf
    • KV status bytes - Issue #754 @scottf
    • List materialized views #765 @scottf

    Examples

    • Example to show handling pub acks in a separate thread than the publish. #748 @scottf
    Source code(tar.gz)
    Source code(zip)
  • 2.16.0(Sep 19, 2022)

    General

    Retroactive minor bump for Server V2.9.0 features and experimental object store api.

    JetStream

    • Ability to opt-out of using Server v2.9.0 consumer create api #728 @scottf
    Source code(tar.gz)
    Source code(zip)
  • 2.15.7(Sep 15, 2022)

    IMPORTANT

    This release uses a new consumer create API when interacting with nats-server version 2.9.0 or higher. This changes the subjects used by the client to create consumers, which might in some cases require changes in access and import/export configuration.

    JetStream / Management

    • Get Message Enhancement #696 @scottf
    • No Erase option on message delete #698 @scottf
    • Support v2.9.0 Get Direct Message feature #701 #703 @scottf
    • Support v2.9.0 Consumer Create feature #723 #725 @scottf

    Key Value

    • Fix bug to return null instead of entry on get of deleted or purged key #700 @scottf
    • Allow direct configuration for KV #718 #724 @scottf

    Object Store

    • Initial implementation, experimental. #705 #714 #720 @scottf

    Core

    • Static Memory Auth Handler #702 @scottf
    • Support v2.9.0 stream configuration republish #709 @scottf
    Source code(tar.gz)
    Source code(zip)
  • 2.15.6(Jul 29, 2022)

    Core

    • better request timeout management #693 @scottf

    JetStream

    • support num_replicas and mem_storage in consumer configuration #689 @goku321 @scottf

    Misc

    • Change example to have more flexibility on message size #690 @scottf
    Source code(tar.gz)
    Source code(zip)
  • 2.15.5(Jul 4, 2022)

    Core

    • Accept encoded connection urls #674 @scottf
    • Only track duplicate responses when advanced tracking is on #659 @scottf

    JetStream

    • revert ConsumerConfiguration changes where some fields were downgraded #685 @scottf
    • consumer info change to sequence_info from sequence_pair #679 @scottf
    • consumer filter subject is now modifiable #676 @scottf
    • handle updated account stats #668 @scottf
    • Ability to create an External object #661 @scottf

    KV

    • ability to update bucket config #662 @scottf

    Experimental

    • expose management getStreamNamesBySubjectFilter #681 @scottf
    • experimental pull reader #683 @scottf

    Tests

    • Add test for NKey.clear #663 @lacinoire

    Misc

    • remove comments that say durable is required during pull #675 @scottf
    • better push queue example #670 @scottf
    • fix inactive threshold doc #660 @scottf
    Source code(tar.gz)
    Source code(zip)
  • 2.15.4(Jul 3, 2022)

    Core

    • Accept encoded connection urls #674 @scottf
    • Only track duplicate responses when advanced tracking is on #659 @scottf

    JetStream

    • consumer info change to sequence_info from sequence_pair #679 @scottf
    • consumer filter subject is now modifiable #676 @scottf
    • handle updated account stats #668 @scottf
    • Ability to create an External object #661 @scottf

    KV

    • ability to update bucket config #662 @scottf

    Experimental

    • expose management getStreamNamesBySubjectFilter #681 @scottf
    • experimental pull reader #683 @scottf

    Tests

    • Add test for NKey.clear #663 @lacinoire

    Misc

    • remove comments that say durable is required during pull #675 @scottf
    • better push queue example #670 @scottf
    • fix inactive threshold doc #660 @scottf
    Source code(tar.gz)
    Source code(zip)
  • 2.15.3(Jun 6, 2022)

  • 2.15.2(Jun 1, 2022)

    JetStream

    • Pull config changes, ephemeral pull, unit tests PR #645 @scottf
    • Server urls connection management PR #648 @scottf
      • Architecture issue 113 Add option to ignore discovered urls
      • ServersToTryProvider provide a way that a user can provide a complete custom implementation to provide the server urls to try on connect / reconnect. Tiered servers could be implemented this way. EXPERIMENTAL feature.
    • EXPERIMENTAL PullRequestOptions PR #649 @scottf
    Source code(tar.gz)
    Source code(zip)
  • 2.15.1(May 21, 2022)

  • 2.15.0(May 4, 2022)

    The order of creating a subscription on the server and creating a consumer on the server matters. Once the consumer is created, there is interest and the server tries to deliver. But if the subscription is not created, the messages are delivered to...nowhere, but are considered delivered.

    This was not strictly a problem but it was a race - if the subscription was ready before the consumer was sent messages, then things went fine. Unit test didn't fail. But when we were testing against NGS and in clusters with mixes of JetStream and non-Jetstream servers, the consumer was always ready because of simple latency.

    So now the server subscription is always made first avoiding the problem altogether.

    See PR #639

    Source code(tar.gz)
    Source code(zip)
  • 2.14.2(May 4, 2022)

    Improvements

    PR #637

    • Added additional validation (unit testing) in relation to PR #635 Improve subscription creation with existing durable to be smarter when comparing provided configuration with server configuration.
    • Added more information to the exception message text by including a list of fields that caused the issue.
    Source code(tar.gz)
    Source code(zip)
  • 2.14.1(Apr 26, 2022)

    Client Parity

    PR #630 Support for server Consumer feature Backoff Lists.

    Improvements

    Issue #616 / PR #617 Support for timeout propagation in async requests PR #630 Surfaced delay for nak requests PR #631 Tune kv subscribe supported functions keys / history / purge PR #634 Added client side limit checks option to allow turning off client side checks which forces check to server. Default behavior is the same. PR #635 Improve subscription creation with existing durable to be smarter when comparing provided configuration with server configuration.

    Bug Fixes

    Issue #621 / PR #622 Fixed kv key with dot as part of the key

    Documentation etc.

    PR #612 Version change and miscellaneous documentation. PR #629 Rate Limit is bytes per second (bps) not messages per second.

    Source code(tar.gz)
    Source code(zip)
  • 2.14.0(Mar 8, 2022)

    Key Value

    • KV API Release

    JetStream

    • Allow null or empty subject when appropriate while subscribing / binding
    • new JetStreamManagement api StreamInfo getStreamInfo(String streamName, StreamInfoOptions options)
    • support Stream Configuration and Stream State to reflect server changes up to server V2.7.3
    • support Consumer Configuration reflect server changes up to server V2.7.3
    • Fixed bug with pull subscribe fetch and iterate where it could wait twice the expiration time and improved implementation to reflect server changes in pull behavior.
    • Added combo pull nowait + expires primitive api to match server pull changes.

    Miscellaneous

    • Addressed Info level Cure53 audit item regarding version string.
    • Moved JsMultiTool out of example to the example repo.
    • Added NatsJsPushSubAsyncQueueDurable example program.
    • Unit test improvements to prevent flappers
    Source code(tar.gz)
    Source code(zip)
  • 2.13.2(Jan 6, 2022)

  • 2.13.1(Nov 2, 2021)

    JetStream

    • This release fixes a bug found in the new subscription enhancements where the comparison of default configuration failed to validate properly against an existing (durable) consumer configuration.

    • There are also minor enhancements to the JsMulti tool

    Source code(tar.gz)
    Source code(zip)
  • 2.13.0(Oct 27, 2021)

  • 2.12.0(Sep 8, 2021)

    This release is the first release to support v2.4.0 of the NATS server. The change covers how queueing is supported in JetStream using the Deliver Group subscribe option.

    Source code(tar.gz)
    Source code(zip)
  • 2.11.6(Aug 25, 2021)

    Overview

    1. Key Value (KV) Beta: This release includes a beta version of the Key Value functionality. There were multiple PR's involved in KV including new interfaces and new api / protocol enhancements designed to support KV
    2. Support for API error code allowing server generated errors to be identified by number instead of text.
    3. Stream and Consumer descriptions
    4. Publish expectation last subject sequence
    5. Advanced stream purge functionality
    6. Primitive pull functionality marked as "advanced"
    Source code(tar.gz)
    Source code(zip)
  • 2.11.5(Jul 6, 2021)

  • 2.11.5.beta3(Jun 22, 2021)

  • 2.11.4(Jun 1, 2021)

  • 2.11.3(May 24, 2021)

    Pull Requests

    [ENHANCEMENT] PR #472 / #477 benchmark improvements (@scottf) [ENHANCEMENT] PR #473 performance improvements(@scottf) [FIXED] PR #475 fixed filter subject (@scottf) [EXAMPLES] PR #478 Clarify examples with deliver subjects (@scottf)

    Source code(tar.gz)
    Source code(zip)
  • 2.11.2(May 17, 2021)

    Pull Requests

    [ENHANCEMENT] PR #470 JsMultiTool and AutoBench Reporting Enhancements (@scottf) [ENHANCEMENT] PR #468 duplicates and orphans (@scottf) [FEATURE] PR #467 / #471 Heartbeat and Flow Control (@scottf) [FIXED] PR #466 JsMultiTool Queue Fix (@scottf)

    Source code(tar.gz)
    Source code(zip)
  • 2.11.1(May 6, 2021)

  • 2.11.0(Apr 30, 2021)

    Issue Bug Fixes

    • [FIXED] Issue #340 No connection possible when using multiple servers PR #455 (@scottf)

    Pull Requests

    • [FIXED] PR #451 Header status improvements (@scottf)
    • [ENHANCEMENT] PR #452 handle no ack publishing (@scottf)
    • [ENHANCEMENT] PR #456 switched to jnats-server-runner library (@scottf)
    • [ENHANCEMENT] PR #446 improve cleanup of async responses (@scottf)

    Issues General Closed

    • [NON ISSUE] Issue #298 NatsConnection does not report SSL error (@scottf)
    • [WILL NOT IMPLEMENT] Issue #272 Add ability to publish byte arrays with specified offset and length (@scottf)
    • [DOCUMENTED] Issue #316 Failure creating a subscription on a (fairly) new connection (@scottf)
    • [NON ISSUE] Issue #344 Performance issue when publishing to certain topics (@scottf)
    • [WILL NOT IMPLEMENT] Issue #373 Why not netty for networking? (@sasbury)
    • [PRE-RELEASE FEATURE REMOVED] Issue #388 In the jetstream subscriber examples... (@scottf)
    • [DOCUMENTED] Issue #402 Unable to connect to NATS server via Android Studio
    • [DOCUMENTED] Issue #445 NatsConnection.request(Message) does not use Message.replyTo (@scottf)
    • [DOCUMENTED] Issue #423 createContext() not documented (@scottf)
    Source code(tar.gz)
    Source code(zip)
  • 2.10.0(Apr 1, 2021)

    Overview

    1. JetStream (message and management) support added.
    2. Miscellaneous bug fixes.
    3. Examples and benchmarks updated
    4. Improved unit tests with reusable scaffolding
    5. General Improvements
    6. Switched default branch from "master" to "main"

    Non JetStream Pull Requests

    • [GENERAL] PR #358 Use OS Default SecureRandom (@scottf)
    • [BUILD] Issue #360 Automatic-Module-Name clause added to jar manifest. (@bjorndarri)
    • [BUILD] PR #365 gradle minor improvements, support windows (@scottf)
    • [TEST] PR #375 fix test failing because of timeout that aren't testing timing (@scottf)
    • [GENERAL] PR #380 Add a flushBuffer API (@ColinSullivan1)
    • [GENERAL] PR #383 nuid speed improvements (@scottf)
    • [GENERAL] PR #391 reconnect-jitter-handler-serverinfo-tests (@scottf)

    Issue Features

    • [JETSTREAM] Issue #335 Add Message Headers (@scottf)
    • [GENERAL] Issue #336 Support no-responders (@scottf)
    • [JETSTREAM] Issue #353 Jetstream APIS (@ColinSullivan1) (@scottf)
    • [BUILD] Issue #355 Automatic module name (@bjorndarri)
    • [GENERAL] Issue #377 Add a flushBuffer Connection API (@ColinSullivan1) Added in PR #380
    • [JETSTREAM] Issue #393 Create Asynchronous Jetstream.Publish API (@scottf) Added in PR #398
    • [JETSTREAM] Issue #396 Jetstream Consumer Delete API (@scottf) Added in PR #408
    • [JETSTREAM] Issue #412 Add a JS management API to get consumer info (@scottf) Added in PR #413

    Issue Bug Fixes

    • [FIXED] Issue #424 ERROR: Subject remapping requires Options.oldRequestStyle()... (@scottf)
    • [FIXED] Issue #345 "unable to stop reader thread" log message (@ColinSullivan1) Fixed in PR #427
    • [FIXED] Issue #310 NatsConnection.close unnecessarily sleeps for one second (@scottf)

    Issues General

    • [COMMENTED] Issue #341 Why is a char[] more secure then a String for connection auth details? (@scottf)
    • [OTHER] Issue #384 Validations on expectedLastSeqence, expectedStream and expectedLastMsgId are not working for jetstream producer (fixed by nats-server PR #1787)
    Source code(tar.gz)
    Source code(zip)
Owner
NATS - The Cloud Native Messaging System
NATS is a simple, secure and performant communications system for digital systems, services and devices.
NATS - The Cloud Native Messaging System
RabbitMQ Java client

RabbitMQ Java Client This repository contains source code of the RabbitMQ Java client. The client is maintained by the RabbitMQ team at Pivotal. Depen

RabbitMQ 1.1k Jan 7, 2023
A command line client for Kafka Connect

kcctl -- A CLI for Apache Kafka Connect This project is a command-line client for Kafka Connect. Relying on the idioms and semantics of kubectl, it al

Gunnar Morling 274 Dec 19, 2022
CookieClient is a utility client for anarchy servers

CookieClient CookieClient is a utility client for anarchy servers. Its a forge mod so you need forge to run it. Currently supported versions: 1.12.2 D

null 82 Dec 4, 2022
A command line client for Kafka Connect

?? kcctl – Your Cuddly CLI for Apache Kafka Connect This project is a command-line client for Kafka Connect. Relying on the idioms and semantics of ku

kcctl 274 Dec 19, 2022
Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

EventBus EventBus is a publish/subscribe event bus for Android and Java. EventBus... simplifies the communication between components decouples event s

Markus Junginger 24.2k Jan 3, 2023
Pure Java ZeroMQ

JeroMQ Pure Java implementation of libzmq (http://zeromq.org). Features Based on libzmq 4.1.7. ZMTP/3.0 (http://rfc.zeromq.org/spec:23). tcp:// protoc

The ZeroMQ project 2.2k Jan 9, 2023
Java binding for ZeroMQ

What is JZMQ? This is the Java language binding for libzmq (aka ZeroMQ, 0MQ). The latest javadocs. Building and Installing JZMQ To build you need to h

The ZeroMQ project 577 Dec 11, 2022
A mod for Fabric that ports Bedrock Edition mechanics to Java Edition. 1.16.x

bedrock-mechanics A mod for Fabric that ports Bedrock Edition mechanics to Java Edition. The controller support should be working on any controller by

Pedro Henrique 6 Oct 24, 2021
KC4Streams - a simple Java library that provides utility classes and standard implementations for most of the Kafka Streams pluggable interfaces

KC4Streams (which stands for Kafka Commons for Streams) is a simple Java library that provides utility classes and standard implementations for most of the Kafka Streams pluggable interfaces.

StreamThoughts 2 Mar 2, 2022
Kafka example - a simple producer and consumer for kafka using spring boot + java

Kafka example - a simple producer and consumer for kafka using spring boot + java

arturcampos 1 Feb 18, 2022