Class Nats


  • public class Nats
    extends java.lang.Object
    The Nats class is the entry point into the NATS client for Java. This class is used to create a connection to the NATS server. Connecting is a synchronous process, with a new asynchronous version available for experimenting.

    Simple connections can be created with a URL, while more control is provided when an Options object is used. There are a number of options that effect every connection, as described in the Options documentation.

    At its simplest, you can connect to a nats-server on the local host using the default port with:

    Connection nc = Nats.connect()

    and start sending or receiving messages immediately after that.

    While the simple case relies on a single URL, the options allows you to configure a list of servers that is used at connect time and during reconnect scenarios.

    NATS supports TLS connections. This library relies on the standard SSLContext class to configure SSL certificates and trust managers, as a result there are two steps to setting up a TLS connection, configuring the SSL context and telling the library which one to use. Several options are provided for each. To tell the library to connect with TLS:

    • Pass a tls:// URL to the connect method, or as part of the options. The library will use the default SSLContext for both the client certificates and trust managers.
    • Call the secure method on the options builder, again the default SSL Context is used.
    • Call sslContext when building your options. Your context will be used.
    • Pass an opentls:// url to the connect method, or in the options. The library will create a special SSLContext that has no client certificates and trusts any server. This is less secure, but useful for testing and behind a firewall.
    • Call the opentls method on the builder when creating your options, again the all trusting, non-verifiable client is created.

    To set up the default context for tls:// or secure you can:

    • Configure the default using System properties, i.e. javax.net.ssl.keyStore.
    • Set the context manually with the SSLContext setDefault method.

    If the server is configured to verify clients, the opentls mode will not work, and the other modes require a client certificate to work.

    Authentication, if configured on the server, is managed via the Options as well. However, the url passed to connect() can provide a user/password pair or a token using the forms: nats://user:password@server:port and nats://token@server:port.

    Regardless of the method used a Connection object is created, and provides the methods for sending, receiving and dispatching messages.

    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.lang.String CLIENT_LANGUAGE
      Current language of the library - "java"
      static java.lang.String CLIENT_VERSION
      Current version of the library - "2.6.1"
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static Connection connect()
      Connect to the default URL, Options.DEFAULT_URL, with all of the default options.
      static Connection connect​(Options options)
      Options can be used to set the server URL, or multiple URLS, callback handlers for various errors, and connection events.
      static Connection connect​(java.lang.String url)
      The Java client generally expects URLs of the form nats://hostname:port
      static void connectAsynchronously​(Options options, boolean reconnectOnConnect)
      Try to connect in another thread, a connection listener is required to get the connection.
      static AuthHandler credentials​(java.lang.String credsFile)
      Create an authhandler from a creds file.
      static AuthHandler credentials​(java.lang.String jwtFile, java.lang.String nkeyFile)
      Create an authhandler from a jwt file and an nkey file.
      static AuthHandler staticCredentials​(char[] jwt, char[] nkey)
      Create an auth handler from an nkey and an option JWT.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • CLIENT_VERSION

        public static final java.lang.String CLIENT_VERSION
        Current version of the library - "2.6.1"
        See Also:
        Constant Field Values
      • CLIENT_LANGUAGE

        public static final java.lang.String CLIENT_LANGUAGE
        Current language of the library - "java"
        See Also:
        Constant Field Values
    • Method Detail

      • connect

        public static Connection connect()
                                  throws java.io.IOException,
                                         java.lang.InterruptedException
        Connect to the default URL, Options.DEFAULT_URL, with all of the default options.

        This is a synchronous call, and the connection should be ready for use on return there are network timing issues that could result in a successful connect call but the connection is invalid soon after return, where soon is in the network/thread world.

        If the connection fails, an IOException is thrown

        See connect(Options) for more information on exceptions.

        Returns:
        the connection
        Throws:
        java.io.IOException - if a networking issue occurs
        java.lang.InterruptedException - if the current thread is interrupted
      • connect

        public static Connection connect​(java.lang.String url)
                                  throws java.io.IOException,
                                         java.lang.InterruptedException
        The Java client generally expects URLs of the form nats://hostname:port

        but also allows urls with a user password nats://user:pass@hostname:port.

        or token in them nats://token@hostname:port.

        Moreover, you can initiate a TLS connection, by using the `tls` schema, which will use the default SSLContext, or fail if one is not set. For testing and development, the `opentls` schema is support when the server is in non-verify mode. In this case, the client will accept any server certificate and will not provide one of its own.

        This is a synchronous call, and the connection should be ready for use on return there are network timing issues that could result in a successful connect call but the connection is invalid soon after return, where soon is in the network/thread world.

        If the connection fails, an IOException is thrown

        See connect(Options) for more information on exceptions.

        Parameters:
        url - the url of the server, ie. nats://localhost:4222
        Returns:
        the connection
        Throws:
        java.io.IOException - if a networking issue occurs
        java.lang.InterruptedException - if the current thread is interrupted
      • connect

        public static Connection connect​(Options options)
                                  throws java.io.IOException,
                                         java.lang.InterruptedException
        Options can be used to set the server URL, or multiple URLS, callback handlers for various errors, and connection events.

        This is a synchronous call, and the connection should be ready for use on return there are network timing issues that could result in a successful connect call but the connection is invalid soon after return, where soon is in the network/thread world.

        If the connection fails, an IOException is thrown

        As of 2.6 the connect call with throw an io.nats.AuthenticationException if an authentication error occurred during connect, and the connect failed. Because multiple servers are tried, this exception may not indicate a problem on the "last server" tried, only that all the servers were tried and at least one failed because of authentication. In situations with heterogeneous authentication for multiple servers you may need to use an ErrorListener to determine which one had the problem. Authentication failures are not immediate connect failures because of the server list, and the existing 2.x API contract.

        As of 2.6.1 authentication errors play an even stronger role. If a server returns an authentication error twice without a successful connection, the connection is closed. This will require a reconnect scenario, since the initial connection only tries each server one time. However, if you have two servers S1 and S2, and S1 returns and authentication error on connect, but S2 succeeds. Later, if S2 fails and S1 returns the same error the connection will be closed. However, if S1 succeeds on reconnect the "last error" will be cleared so it would be allowed to fail again in the future.

        Parameters:
        options - the options object to use to create the connection
        Returns:
        the connection
        Throws:
        java.io.IOException - if a networking issue occurs
        java.lang.InterruptedException - if the current thread is interrupted
      • connectAsynchronously

        public static void connectAsynchronously​(Options options,
                                                 boolean reconnectOnConnect)
                                          throws java.lang.InterruptedException
        Try to connect in another thread, a connection listener is required to get the connection.

        Normally connect will loop through the available servers one time. If reconnectOnConnect is true, the connection attempt will repeat based on the settings in options, including indefinitely.

        If there is an exception before a connection is created, and the error listener is set, it will be notified with a null connection.

        This method is experimental, please provide feedback on its value.

        Parameters:
        options - the connection options
        reconnectOnConnect - if true, the connection will treat the initial connection as any other and attempt reconnects on failure
        Throws:
        java.lang.IllegalArgumentException - if no connection listener is set in the options
        java.lang.InterruptedException - if the current thread is interrupted
      • credentials

        public static AuthHandler credentials​(java.lang.String credsFile)
        Create an authhandler from a creds file. The handler will read the file each time it needs to respond to a request and clear the memory after. This has a small price, but will only be encountered during connect or reconnect. The creds file has a JWT - generally commented with a separator - followed by an nkey - also with a separator.
        Parameters:
        credsFile - a file containing a user JWT and an nkey
        Returns:
        an authhandler that will use the creds file to load/clear the nkey and jwt as needed
      • credentials

        public static AuthHandler credentials​(java.lang.String jwtFile,
                                              java.lang.String nkeyFile)
        Create an authhandler from a jwt file and an nkey file. The handler will read the files each time it needs to respond to a request and clear the memory after. This has a small price, but will only be encountered during connect or reconnect.
        Parameters:
        jwtFile - a file containing a user JWT, may or may not contain separators
        nkeyFile - a file containing a user nkey that matches the JWT, may or may not contain separators
        Returns:
        an authhandler that will use the creds file to load/clear the nkey and jwt as needed
      • staticCredentials

        public static AuthHandler staticCredentials​(char[] jwt,
                                                    char[] nkey)
        Create an auth handler from an nkey and an option JWT. This credentials object is static, and will not change over the course of its lifetime. Create a custom AuthHandler or use the file-based handler for dynamic credentials.
        Parameters:
        jwt - the contents of a user JWT file (optional if nkey authentication is being used)
        nkey - an nkey seed
        Returns:
        an authhandler that will return the JWT, public key or sign a nonce appropriately