
NATS - Java Client
Examples and other documentation...
- Java API Docs - the latest Java API docs.
- NATS by Example is an evolving collection of runnable, cross-client reference examples for NATS.
- The examples directory covers basic api use.
- The Java Nats Examples GitHub repo, a collection of simple use case examples.
Table of Contents
Important
2.27.0 Changes to secure connection behavior
TLS hostname verification is on by default: a connection to a server whose certificate does not name the host in the url now fails. See Version 2.27.0 Hostname Verification On By Default for who is affected and how to opt out.
The servers a cluster advertises are listed, verified over TLS and reconnected to by new rules, TLS 1.2 is the floor on every connection, and url passwords are hidden from events and errors. See Version 2.27.0 TLS Discovery and Reconnect and the full notes in RELEASE_NOTES_ADR40.md.
Client and Orbit
NATS client functionality is split across two layers: the core client
(nats.java, this repo) and Orbit,
a separate set of artifacts with higher-level utilities.
The split exists so the core can stay small, stable, and consistent across
NATS clients in every language, while Orbit can iterate quickly on
opinionated abstractions without dragging the core API along for the ride.
Core client (nats.java)
- Direct API over Core NATS and JetStream as exposed by
nats-server.
- Lightweight, unopinionated, performance-oriented.
- API surface kept in parity with other official NATS clients
(Rust, Go, .NET, JS, Python, C). A feature shipped here should look
the same shape everywhere.
- Stable, conservative versioning. Breaking changes are rare and deliberate.
Orbit (orbit.java)
- Higher-level, opinionated abstractions built on top of the core client.
- Per-artifact versioning, so an experimental utility can iterate
without bumping every other piece.
- Free to be language-specific: a Java-idiomatic API does not need to match
the equivalent in other languages.
- May lag, omit, or extend cross-client parity items.
What goes where?
| Concern |
Core (nats.java) |
Orbit |
| Connect, publish, subscribe, request/reply |
✅ |
|
| JetStream publish, consumers, streams, KV, OS |
✅ |
|
| Service API (request/reply micro-services) |
✅ |
|
| Wire-protocol coverage, auth, TLS, reconnection |
✅ |
|
| Cross-client parity, conservative semver |
✅ |
|
| Opinionated helpers / sugar over core APIs |
|
✅ |
| New experimental patterns (e.g. partitioned groups) |
|
✅ |
| KV codecs, distributed counters, NATS contexts |
|
✅ |
| Java-idiomatic abstractions with no parity mandate |
|
✅ |
| Per-utility versioning, faster API churn allowed |
|
✅ |
Rule of thumb: if it is a thin mapping of something nats-server
already speaks and every official client must expose it, it belongs in
core. If it is a pattern, helper, or abstraction layered on top, it
belongs in Orbit.
Layering
┌──────────────────────────────────────────────────────┐
│ Application code │
└──────────────┬───────────────────────────┬───────────┘
│ │
▼ ▼
┌───────────────────┐ ┌───────────────────┐
│ Orbit artifacts │ uses │ nats.java (core) │
│ (opinionated, │──────▶│ (parity, stable, │
│ per-art semver) │ │ protocol-level) │
└───────────────────┘ └─────────┬─────────┘
│
▼
┌─────────────┐
│ nats-server │
└─────────────┘
Simplification
There is a new simplified api that makes working with streams and consumers well, simpler! Simplification is released as of 2.16.14.
Check out the examples:
Consumer Info Calls
From JetStreamManagement:
ConsumerInfo getConsumerInfo(String streamName, String consumerName) throws IOException, JetStreamApiException;
We've seen this api get used to track consumers in order to execute business logic and to understand the state of the system.
When there are not that many consumers and the system is not that busy, this is fine, but as the number of consumers grow,
this call become expensive in time and resources for the server to resolve.
We suggest that whenever possible, use metadata from a message for that particular consumer
since it often already contains the needed information and does not require a server call.
You can bubble this information up as you need.
Service Framework
The service API allows you to easily build NATS services. The Service Framework is released as of 2.16.14
The Services Framework introduces a higher-level API for implementing services with NATS. NATS has always been a strong technology on which to build services,
as they are straightforward to write, are location and DNS independent, and can be scaled up or down by simply adding or removing instances of the service.
The Services Framework further streamlines their development by providing observability and standardization.
The Service Framework allows your services to be discovered and queried for status without additional work.
Check out the ServiceExample
Subject Validation
Subject validation is changed as of 2.25.1. Up until now, subject validation has been strict.
This means that when subjects were presented for instance in publish or subscribe calls,
strict validation was applied. While this is great for some use cases, for instance when
giving the ability of an application user to set a subject, it's generally not necessary.
And in that case, you may want to validate the subject as you would to prevent a sql injection.
If you tightly control your subjects, you may prefer no validation at all.
Options now specifies lenient validation by default and gives you the ability
to set the validation to none or strict if that makes sense for your application.
This can be accomplished with Options.Builder methods:
public Builder noSubjectValidation();
public Builder strictSubjectValidation();
of via properties
noSubjectValidation=true
strictSubjectValidation=true
Behavior and Benchmark over 37 million passes...
| Type |
Millis Total |
Nanos Per |
Behavior |
| Lenient |
7393 |
199.81 |
Space, Tab, CR, LF are invalid |
| Strict |
15272 |
413.76 |
Lenient plus check for improper formation of segments or wildcard use |
| None |
2155 |
58.24 |
Only checks for string not being null or empty when the subject is required |
Connection Options Executors
An Options instance resolves the executors it uses once and caches them on the Options instance,
so if you reuse a single Options to create more than one Connection, those connections share the
same executors rather than each getting their own.
Executors the client creates for you — the defaults, or ones built from a supplied ThreadFactory —
create threads on demand and are owned and shut down by the client, so sharing an Options across
connections does not starve them of threads. If instead you supply your own ExecutorService (e.g. via
executor, connectExecutor, callbackExecutor, readerExecutor, or writerExecutor), the client
uses it as-is and never shuts it down — you own its lifecycle — and because a shared Options routes
every connection through that one executor, make sure it can run them concurrently (don't, for example,
share a single-thread executor across many connections). When in doubt, give each connection its own
Options instance (the builder makes this cheap).
One sharp edge to be aware of with the general executor: the reader, the writer, and every Dispatcher
run as concurrent, long-lived tasks on it, so it must be able to run several tasks at once. Do not
supply a single-thread (or tightly bounded) executor — the reader's loop runs for the life of the
connection and would starve the writer, effectively deadlocking it. If you need to limit threads, isolate
the protocol I/O with readerExecutor/writerExecutor (or readerThreadFactory/writerThreadFactory)
rather than shrinking the general executor.
Recent Version Notes
Version 2.27.0 Hostname Verification On By Default
Starting with 2.27.0, the client checks that the certificate a server presents was issued for the host in the url you connect with. Before 2.27.0 it did not: any certificate your trust store accepted was accepted for any host, and opentls accepted any certificate at all. The check applies to every TLS connection, including opentls, and to servers the client discovers from the cluster, not only the ones in your options.
When the certificate does not name the host, the connection fails and the error names the host it was looking for, for example No subject alternative names matching IP address 10.0.0.5 found.
You are not affected if you do not use TLS, or if you connect by a name, such as tls://nats.example.com:4222, and the certificate was issued for that name. This is the normal case with a certificate from a public or private CA.
You are affected if:
- You connect by ip address, such as
tls://10.0.0.5:4222, and the certificate does not list that ip address as a subject alternative name. Certificates issued for a hostname usually do not.