Class Options.Builder
- java.lang.Object
-
- io.nats.client.Options.Builder
-
- Enclosing class:
- Options
public static class Options.Builder extends java.lang.Object
Options are created using a Builder. The builder supports chaining and will create a default set of options if no methods are calls. The builder can also be created from a properties object using the property names defined with the prefix PROP_ in this class.new Options.Builder().build()
is equivalent to callingNats.connect()
.A common usage for testing might be
new Options.Builder().server(myserverurl).noReconnect.build()
-
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description Options.Builder
authHandler(AuthHandler handler)
Set theAuthHandler
to sign the server nonce for authentication in nonce-mode.Options.Builder
bufferSize(int size)
Sets the initial size for buffers in the connection, primarily for testing.Options
build()
Build an Options object from this Builder.Options.Builder
connectionListener(ConnectionListener listener)
Set theConnectionListener
to receive asynchronous notifications of disconnect events.Options.Builder
connectionName(java.lang.String name)
Set the connection's optional Name.Options.Builder
connectionTimeout(java.time.Duration time)
Set the timeout for connection attempts.Options.Builder
dataPortType(java.lang.String dataPortClassName)
The class to use for this connections data port.Options.Builder
errorListener(ErrorListener listener)
Set theErrorListener
to receive asynchronous error events related to this connection.Options.Builder
executor(java.util.concurrent.ExecutorService executor)
Set theExecutorService
used to run threaded tasks.Options.Builder
inboxPrefix(java.lang.String prefix)
Set the connection's inbox prefix.Options.Builder
maxControlLine(int bytes)
Set the maximum length of a control line sent by this connection.Options.Builder
maxPingsOut(int max)
Set the maximum number of pings the client can have in flight.Options.Builder
maxReconnects(int max)
Set the maximum number of reconnect attempts.Options.Builder
noEcho()
Turn off echo.Options.Builder
noRandomize()
Turn off server pool randomization.Options.Builder
noReconnect()
Equivalent to calling maxReconnects with 0,maxReconnects
.Options.Builder
oldRequestStyle()
Turn on the old request style that uses a new inbox and subscriber for each request.Options.Builder
opentls()
Set the SSL context to one that accepts any server certificate and has no client certificates.Options.Builder
pedantic()
Turn on pedantic mode for the server, in relation to this connection.Options.Builder
pingInterval(java.time.Duration time)
Set the interval between attempts to pings the server.Options.Builder
reconnectBufferSize(long size)
Set the maximum number of bytes to buffer in the client when trying to reconnect.Options.Builder
reconnectWait(java.time.Duration time)
Set the time to wait between reconnect attempts to the same server.Options.Builder
requestCleanupInterval(java.time.Duration time)
Set the interval between cleaning passes on outstanding request futures that are cancelled or timeout in the application code.Options.Builder
secure()
Sets the options to use the default SSL Context, if it exists.Options.Builder
server(java.lang.String serverURL)
Add a server to the list of known servers.Options.Builder
servers(java.lang.String[] servers)
Add an array of servers to the list of known servers.Options.Builder
sslContext(javax.net.ssl.SSLContext ctx)
Set the SSL context, requires that the server supports TLS connections and the URI specifies TLS.Options.Builder
supportUTF8Subjects()
The client protocol is not clear about the encoding for subject names.Options.Builder
token(char[] token)
Set the token for token-based authentication.Options.Builder
token(java.lang.String token)
Deprecated.use the char[] version instead for better securityOptions.Builder
traceConnection()
Enable connection trace messages.Options.Builder
turnOnAdvancedStats()
Turn on advanced stats, primarily for test/benchmarks.Options.Builder
userInfo(char[] userName, char[] password)
Set the username and password for basic authentication.Options.Builder
userInfo(java.lang.String userName, java.lang.String password)
Deprecated.use the char[] version instead for better securityOptions.Builder
verbose()
Turn on verbose mode with the server.
-
-
-
Constructor Detail
-
Builder
public Builder()
Constructs a new Builder with the default values.One tiny clarification is that the builder doesn't have a server url. When
build()
is called on a default builder it will add thedefault url
to its list of servers before creating the options object.
-
Builder
public Builder(java.util.Properties props) throws java.lang.IllegalArgumentException
Constructs a newBuilder
from aProperties
object.If
PROP_SECURE
is set, the builder will try to to get the default contextgetDefault()
. If a context can't be found, no context is set and an IllegalArgumentException is thrown.Methods called on the builder after construction can override the properties.
- Parameters:
props
- theProperties
object- Throws:
java.lang.IllegalArgumentException
-
-
Method Detail
-
server
public Options.Builder server(java.lang.String serverURL)
Add a server to the list of known servers.- Parameters:
serverURL
- the URL for the server to add- Returns:
- the Builder for chaining
- Throws:
java.lang.IllegalArgumentException
- if the url is not formatted correctly.
-
servers
public Options.Builder servers(java.lang.String[] servers)
Add an array of servers to the list of known servers.- Parameters:
servers
- A list of server URIs- Returns:
- the Builder for chaining
- Throws:
java.lang.IllegalArgumentException
- if any url is not formatted correctly.
-
oldRequestStyle
public Options.Builder oldRequestStyle()
Turn on the old request style that uses a new inbox and subscriber for each request.- Returns:
- the Builder for chaining
-
noRandomize
public Options.Builder noRandomize()
Turn off server pool randomization. By default the server will pick servers from its list randomly on a reconnect. When set to noRandom the server goes in the order they were configured or provided by a server in a cluster update.- Returns:
- the Builder for chaining
-
noEcho
public Options.Builder noEcho()
Turn off echo. If supported by the nats-server version you are connecting to this flag will prevent the server from echoing messages back to the connection if it has subscriptions on the subject being published to.- Returns:
- the Builder for chaining
-
supportUTF8Subjects
public Options.Builder supportUTF8Subjects()
The client protocol is not clear about the encoding for subject names. For performance reasons, the Java client defaults to ASCII. You can enable UTF8 with this method. The server, written in go, treats byte to string as UTF8 by default and should allow UTF8 subjects, but make sure to test any clients when using them.- Returns:
- the Builder for chaining
-
connectionName
public Options.Builder connectionName(java.lang.String name)
Set the connection's optional Name.- Parameters:
name
- the connections new name.- Returns:
- the Builder for chaining
-
inboxPrefix
public Options.Builder inboxPrefix(java.lang.String prefix)
Set the connection's inbox prefix. All inboxes will start with this string.- Parameters:
prefix
- prefix to use.- Returns:
- the Builder for chaining
-
verbose
public Options.Builder verbose()
Turn on verbose mode with the server.- Returns:
- the Builder for chaining
-
pedantic
public Options.Builder pedantic()
Turn on pedantic mode for the server, in relation to this connection.- Returns:
- the Builder for chaining
-
turnOnAdvancedStats
public Options.Builder turnOnAdvancedStats()
Turn on advanced stats, primarily for test/benchmarks. These are visible if you call toString on theStatistics
object.- Returns:
- the Builder for chaining
-
traceConnection
public Options.Builder traceConnection()
Enable connection trace messages. Messages are printed to standard out. This options is for very fine grained debugging of connection issues.- Returns:
- the Builder for chaining
-
secure
public Options.Builder secure() throws java.security.NoSuchAlgorithmException, java.lang.IllegalArgumentException
Sets the options to use the default SSL Context, if it exists.- Returns:
- the Builder for chaining
- Throws:
java.security.NoSuchAlgorithmException
- If the default protocol is unavailable.java.lang.IllegalArgumentException
- If there is no default SSL context.
-
opentls
public Options.Builder opentls() throws java.security.NoSuchAlgorithmException
Set the SSL context to one that accepts any server certificate and has no client certificates.- Returns:
- the Builder for chaining
- Throws:
java.security.NoSuchAlgorithmException
- If the tls protocol is unavailable.
-
sslContext
public Options.Builder sslContext(javax.net.ssl.SSLContext ctx)
Set the SSL context, requires that the server supports TLS connections and the URI specifies TLS.- Parameters:
ctx
- the SSL Context to use for TLS connections- Returns:
- the Builder for chaining
-
noReconnect
public Options.Builder noReconnect()
Equivalent to calling maxReconnects with 0,maxReconnects
.- Returns:
- the Builder for chaining
-
maxReconnects
public Options.Builder maxReconnects(int max)
Set the maximum number of reconnect attempts. Use 0 to turn off auto-reconnect. Use -1 to turn on infinite reconnects.The reconnect count is incremented on a per-server basis, so if the server list contains 5 servers but max reconnects is set to 3, only 3 of those servers will be tried.
This library has a slight difference from some NATS clients, if you set the maxReconnects to zero there will not be any reconnect attempts, regardless of the number of known servers.
The reconnect state is entered when the connection is connected and loses that connection. During the initial connection attempt, the client will cycle over its server list one time, regardless of what maxReconnects is set to. The only exception to this is the experimental async connect method
connectAsynchronously
.- Parameters:
max
- the maximum reconnect attempts- Returns:
- the Builder for chaining
-
reconnectWait
public Options.Builder reconnectWait(java.time.Duration time)
Set the time to wait between reconnect attempts to the same server. This setting is only used by the client when the same server appears twice in the reconnect attempts, either because it is the only known server or by random chance. Note, the randomization of the server list doesn't occur per attempt, it is performed once at the start, so if there are 2 servers in the list you will never encounter the reconnect wait.- Parameters:
time
- the time to wait- Returns:
- the Builder for chaining
-
maxControlLine
public Options.Builder maxControlLine(int bytes)
Set the maximum length of a control line sent by this connection. This value is also configured in the server but the protocol doesn't currently forward that setting. Configure it here so that the client can ensure that messages are valid before sending to the server.- Parameters:
bytes
- the max byte count- Returns:
- the Builder for chaining
-
connectionTimeout
public Options.Builder connectionTimeout(java.time.Duration time)
Set the timeout for connection attempts. Each server in the options is allowed this timeout so if 3 servers are tried with a timeout of 5s the total time could be 15s.- Parameters:
time
- the time to wait- Returns:
- the Builder for chaining
-
pingInterval
public Options.Builder pingInterval(java.time.Duration time)
Set the interval between attempts to pings the server. These pings are automated, and capped bymaxPingsOut()
. As of 2.4.4 the library may way up to 2 * time to send a ping. Incoming traffic from the server can postpone the next ping to avoid pings taking up bandwidth during busy messaging. Keep in mind that a ping requires a round trip to the server. Setting this value to a small number can result in quick failures due to maxPingsOut being reached, these failures will force a disconnect/reconnect which can result in messages being held back or failed. In general, the ping interval should be set in seconds but this value is not enforced as it would result in an API change from the 2.0 release.- Parameters:
time
- the time between client to server pings- Returns:
- the Builder for chaining
-
requestCleanupInterval
public Options.Builder requestCleanupInterval(java.time.Duration time)
Set the interval between cleaning passes on outstanding request futures that are cancelled or timeout in the application code.The default value is probably reasonable, but this interval is useful in a very noisy network situation where lots of requests are used.
- Parameters:
time
- the cleaning interval- Returns:
- the Builder for chaining
-
maxPingsOut
public Options.Builder maxPingsOut(int max)
Set the maximum number of pings the client can have in flight.- Parameters:
max
- the max pings- Returns:
- the Builder for chaining
-
bufferSize
public Options.Builder bufferSize(int size)
Sets the initial size for buffers in the connection, primarily for testing.- Parameters:
size
- the size in bytes to make buffers for connections created with this options- Returns:
- the Builder for chaining
-
reconnectBufferSize
public Options.Builder reconnectBufferSize(long size)
Set the maximum number of bytes to buffer in the client when trying to reconnect. When this value is exceeded the client will start to drop messages. The count of dropped messages can be read from theStatistics
. A value of zero will disable the reconnect buffer, a value less than zero means unlimited. Caution should be used for negative numbers as they can result in an unreliable network connection plus a high message rate leading to an out of memory error.- Parameters:
size
- the size in bytes- Returns:
- the Builder for chaining
-
userInfo
@Deprecated public Options.Builder userInfo(java.lang.String userName, java.lang.String password)
Deprecated.use the char[] version instead for better securitySet the username and password for basic authentication. If the user and password are set in the server URL, they will override these values. However, in a clustering situation, these values can be used as a fallback.- Parameters:
userName
- a non-empty user namepassword
- the password, in plain text- Returns:
- the Builder for chaining
-
userInfo
public Options.Builder userInfo(char[] userName, char[] password)
Set the username and password for basic authentication. If the user and password are set in the server URL, they will override these values. However, in a clustering situation, these values can be used as a fallback.- Parameters:
userName
- a non-empty user namepassword
- the password, in plain text- Returns:
- the Builder for chaining
-
token
@Deprecated public Options.Builder token(java.lang.String token)
Deprecated.use the char[] version instead for better securitySet the token for token-based authentication. If a token is provided in a server URI it overrides this value.- Parameters:
token
- The token- Returns:
- the Builder for chaining
-
token
public Options.Builder token(char[] token)
Set the token for token-based authentication. If a token is provided in a server URI it overrides this value.- Parameters:
token
- The token- Returns:
- the Builder for chaining
-
authHandler
public Options.Builder authHandler(AuthHandler handler)
Set theAuthHandler
to sign the server nonce for authentication in nonce-mode.- Parameters:
handler
- The new AuthHandler for this connection.- Returns:
- the Builder for chaining
-
errorListener
public Options.Builder errorListener(ErrorListener listener)
Set theErrorListener
to receive asynchronous error events related to this connection.- Parameters:
listener
- The new ErrorListener for this connection.- Returns:
- the Builder for chaining
-
connectionListener
public Options.Builder connectionListener(ConnectionListener listener)
Set theConnectionListener
to receive asynchronous notifications of disconnect events.- Parameters:
listener
- The new ConnectionListener for this type of event.- Returns:
- the Builder for chaining
-
executor
public Options.Builder executor(java.util.concurrent.ExecutorService executor)
Set theExecutorService
used to run threaded tasks. The default is a cached thread pool that names threads after the connection name (or a default). This executor is used for reading and writing the underlying sockets as well as for each Dispatcher. The default executor uses a short keepalive time, 500ms, to insure quick shutdowns. This is reasonable since most threads from the executor are long lived. If you customize, be sure to keep the shutdown effect in mind, exectors can block for their keepalive time. The default executor also marks threads with priority normal and as non-daemon.- Parameters:
executor
- The ExecutorService to use for connections built with these options.- Returns:
- the Builder for chaining
-
dataPortType
public Options.Builder dataPortType(java.lang.String dataPortClassName)
The class to use for this connections data port. This is an advanced setting and primarily useful for testing.- Parameters:
dataPortClassName
- a valid and accessible class name- Returns:
- the Builder for chaining
-
build
public Options build() throws java.lang.IllegalStateException
Build an Options object from this Builder.If the Options builder was not provided with a server, a default one will be included
Options.DEFAULT_URL
. If only a single server URI is included, the builder will try a few things to make connecting easier:- If there is no user/password is set but the URI has them,
nats://user:password@server:port
, they will be used. - If there is no token is set but the URI has one,
nats://token@server:port
, it will be used. - If the URI is of the form tls:// and no SSL context was assigned, one is created, see
secure()
. - If the URI is of the form opentls:// and no SSL context was assigned one will be created that does not check the servers certificate for validity. This is not secure and only provided for tests and development.
- Returns:
- the new options object
- Throws:
java.lang.IllegalStateException
- if there is a conflict in the options, like a token and a user/pass
- If there is no user/password is set but the URI has them,
-
-