nats simple test

This is the first article to start studying NATS, so let’s try simple sending and receiving messages first.

NATS Server

Publish Subscribe model
Publish Subscribe model

Use docker-compose.yml to build a test NATS Server.

1
2
3
4
5
6
7
8
version: "3.8"

services:
nats:
container_name: nats
image: nats:2.8.4
ports:
- 4222:4222

then start

1
docker compose up

Java dependency

You need to import NATS Java library in build.gradle

1
2
implementation 'io.nats:jnats:2.15.3'
// https://search.maven.org/artifact/io.nats/jnats

Java code

You can refer to the SDK nats.java instructions here.

Producer

1
2
3
4
5
6
7
8
9
10
import io.nats.client.Connection;
import io.nats.client.Nats;

private void sendMessage() throws Exception {
Connection nc = Nats.connect("nats://localhost:4222");
IntStream.range(0, 10)
.forEach(i -> nc.publish("subject", ("hello world-" + i).getBytes(StandardCharsets.UTF_8)));
nc.flush(Duration.ZERO);
nc.close();
}

Consumer

1
2
3
4
5
6
7
8
9
10
11
12
import io.nats.client.Connection;
import io.nats.client.Dispatcher;
import io.nats.client.Nats;

private void receiveMessage() throws Exception {
Connection nc = Nats.connect("nats://localhost:4222");
Dispatcher d = nc.createDispatcher((msg) -> {
String response = new String(msg.getData(), StandardCharsets.UTF_8);
log.info("Received {}", response);
});
d.subscribe("subject");
}

Simple to understand example of sending and receiving.

Reference

NATS Streams and Services: From Zero to Hero