Giter VIP home page Giter VIP logo

java-nats's Introduction

NATS - Java client

A Java client for the NATS messaging system.

License MIT Build Status Coverage Status Maven Central Javadoc

Dependency Status Reference Status

Installation

Maven Central

Releases

Current stable release (click for pom info): Maven Central

Snapshots

Snapshot releases from the current master branch are uploaded to Sonatype OSSRH (OSS Repository Hosting) with each successful Travis CI build. If you don't already have your pom.xml configured for using Maven snapshots, you'll need to add the following repository to your pom.xml:

<profiles>
  <profile>
     <id>allow-snapshots</id>
        <activation><activeByDefault>true</activeByDefault></activation>
     <repositories>
       <repository>
         <id>snapshots-repo</id>
         <url>https://oss.sonatype.org/content/repositories/snapshots</url>
         <releases><enabled>false</enabled></releases>
         <snapshots><enabled>true</enabled></snapshots>
       </repository>
     </repositories>
   </profile>
</profiles>

Building from source code (this repository)

To clone, compile, and install in your local maven repository (or copy the artifacts from the target/ directory to wherever you need them):

git clone [email protected]:nats-io/java-nats.git
cd java-nats
mvn install

Platform Notes

Linux

We use RNG to generate unique inbox names. A peculiarity of the JDK on Linux (see [JDK-6202721] (https://bugs.openjdk.java.net/browse/JDK-6202721) and JDK-6521844) causes Java to use /dev/random even when /dev/urandom is called for. The net effect is that successive calls to newInbox(), either directly or through calling request() will become very slow, on the order of seconds, making many applications unusable if the issue is not addressed. A simple workaround would be to use the following jvm args.

-Djava.security.egd=file:/dev/./urandom

Basic Usage

import io.nats.client.*;

// Connect to default URL ("nats://localhost:4222")
Connection nc = Nats.connect();

// Simple Publisher
nc.publish("foo", "Hello World".getBytes());

// Simple Async Subscriber
nc.subscribe("foo", m -> {
    System.out.println("Received a message: %s\n", new String(m.getData()));
});

// Simple Sync Subscriber
Subscription sub = nc.subscribeSync("foo");
Message m = sub.nextMsg(timeout);

// Unsubscribing
sub = nc.subscribe("foo");
sub.unsubscribe();

// Requests
msg = nc.request("help", "help me", 10000);

// Replies
nc.subscribe("help", m -> {
    nc.publish(m.getReplyTo(), "I can help!");
});

// Close connection
Connect nc = Nats.connect("nats://localhost:4222");
...
nc.close();

TLS

TLS/SSL connections may be configured through the use of an SSLContext.

	// Set up and load the keystore
	final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
	final char[] keyPassPhrase = "password".toCharArray();
	final KeyStore ks = KeyStore.getInstance("JKS");
	ks.load(classLoader.getResourceAsStream("keystore.jks"), keyPassPhrase);
	kmf.init(ks, keyPassPhrase);

	// Set up and load the trust store
	final char[] trustPassPhrase = "password".toCharArray();
	final KeyStore tks = KeyStore.getInstance("JKS");
	tks.load(classLoader.getResourceAsStream("cacerts"), trustPassPhrase);
	final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
	tmf.init(tks);

	// Get and initialize the SSLContext
	SSLContext c = SSLContext.getInstance(Constants.DEFAULT_SSL_PROTOCOL);
	c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

	// Create NATS options
	Options opts = new Options.Builder()
		.secure()       // Set the secure option, indicating that TLS is required
		.tlsDebug()     // Set TLS debug, which will produce additional console output
		.sslContext(c)  // Set the context for this factory
		.build();

	// Create a new SSL connection
	try (Connection connection = Nats.connect("nats://localhost:1222", opts)) {
		connection.publish("foo", "Hello".getBytes());
		connection.close();
	} catch (Exception e) {
		e.printStackTrace();
	}

Wildcard Subscriptions

// "*" matches any token, at any level of the subject.
nc.subscribe("foo.*.baz", m -> {
    System.out.printf("Msg received on [%s] : %s\n", m.getSubject(), new String(m.getData()));
});

nc.subscribe("foo.bar.*", m -> {
    System.out.printf("Msg received on [%s] : %s\n", m.getSubject(), new String(m.getData()));
});

// ">" matches any length of the tail of a subject, and can only be the last token
// E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22'
nc.subscribe("foo.>", m -> {
    System.out.printf("Msg received on [%s] : %s\n", m.getSubject(), new String(m.getData()));
});

// Matches all of the above
nc.publish("foo.bar.baz", "Hello World");

Queue Groups

// All subscriptions with the same queue name will form a queue group.
// Each message will be delivered to only one subscriber per queue group,
// using queuing semantics. You can have as many queue groups as you wish.
// Normal subscribers will continue to work as expected.

nc.subscribe("foo", "job_workers", m -> {
    received += 1;
});

Advanced Usage

// Flush connection to server, returns when all messages have been processed.
nc.flush()
System.out.println("All clear!");

// flush can also be called with a timeout value.
try {
    flushed = nc.flush(1000);
    System.out.println("All clear!");
} catch (TimeoutException e) {
    System.out.println("Flushed timed out!");
}

// Auto-unsubscribe after MAX_WANTED messages received
final static int MAX_WANTED = 10;
...
sub = nc.subscribe("foo");
sub.autoUnsubscribe(MAX_WANTED);

// Multiple connections
nc1 = Nats.connect("nats://host1:4222");
nc2 = Nats.connect("nats://host2:4222");

nc1.subscribe("foo", m -> {
    System.out.printf("Received a message: %s\n", new String(m.getData()));
});

nc2.publish("foo", "Hello World!");

Clustered Usage

String[] servers = new String[] {
	"nats://localhost:1222",
	"nats://localhost:1223",
	"nats://localhost:1224",
};

// Setup options to include all servers in the cluster
ConnectionFactory cf = new ConnectionFactory();
cf.setServers(servers);

// Optionally set ReconnectWait and MaxReconnect attempts.
// This example means 10 seconds total per backend.
cf.setMaxReconnect(5);
cf.setReconnectWait(2000);

// Optionally disable randomization of the server pool
cf.setNoRandomize(true);

Connection nc = cf.createConnection();

// Setup callbacks to be notified on disconnects and reconnects
nc.setDisconnectedCallback(event -> {
    System.out.printf("Got disconnected from %s!\n", event.getConnection().getConnectedUrl());
});

// See who we are connected to on reconnect.
nc.setReconnectedCallback(event -> {
    System.out.printf("Got reconnected to %s!\n", event.getConnection().getConnectedUrl());
});

// Setup a callback to be notified when the Connection is closed
nc.setClosedCallback( event -> {
    System.out.printf("Connection to %s has been closed.\n", event.getConnection().getConnectedUrl());
});

Logging

This library logs error, warning, and debug information using the Simple Logging Facade for Java (SLF4J) API. This gives you, the downstream user, flexibility to choose which (if any) logging implementation you prefer.

Q: Hey, what the heck is this Failed to load class org.slf4j.impl.StaticLoggerBinder exception?".

A: You're getting that message because slf4j can't find an actual logger implementation in your classpath. Carefully reading the link embedded in those exception messages is highly recommended!

License

(The MIT License)

Copyright (c) 2012-2016 Apcera Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

java-nats's People

Contributors

bsnyder avatar pires avatar jensenbox avatar zshamrock avatar mffrench avatar tylertreat avatar mccraigmccraig avatar

Watchers

James Cloos avatar Garrett Thornburg avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.