Skip to content

Commit 48b8d2c

Browse files
egoebelbeckermaibin
authored andcommitted
BAEL-1545 - Nats Tutorial (eugenp#3904)
1 parent 5b00f0e commit 48b8d2c

3 files changed

Lines changed: 273 additions & 0 deletions

File tree

‎libraries/pom.xml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,13 @@
114114
<artifactId>jetty-webapp</artifactId>
115115
<version>${jetty.version}</version>
116116
</dependency>
117+
118+
<dependency>
119+
<groupId>io.nats</groupId>
120+
<artifactId>jnats</artifactId>
121+
<version>${jnats.version}</version>
122+
</dependency>
123+
117124
<dependency>
118125
<groupId>rome</groupId>
119126
<artifactId>rome</artifactId>
@@ -797,6 +804,8 @@
797804
<commons.dbutils.version>1.6</commons.dbutils.version>
798805
<h2.version>1.4.196</h2.version>
799806
<jetty.version>9.4.8.v20171121</jetty.version>
807+
<jnats.version>1.0</jnats.version>
808+
800809
<httpclient.version>4.5.3</httpclient.version>
801810
<commons.io.version>2.5</commons.io.version>
802811
<flink.version>1.2.0</flink.version>
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
package com.baeldung.jnats;
2+
3+
import io.nats.client.*;
4+
5+
import java.io.IOException;
6+
import java.util.*;
7+
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
10+
11+
public class NatsClient {
12+
13+
private String serverURI;
14+
15+
private Connection natsConnection;
16+
17+
private Map<String, Subscription> subscriptions = new HashMap<>();
18+
19+
private final static Logger log = LoggerFactory.getLogger(NatsClient.class);
20+
21+
public NatsClient() {
22+
this.serverURI = "jnats://localhost:4222";
23+
natsConnection = initConnection(serverURI);
24+
}
25+
26+
27+
public NatsClient(String serverURI) {
28+
29+
if ((serverURI != null) && (!serverURI.isEmpty())) {
30+
this.serverURI = serverURI;
31+
} else {
32+
this.serverURI = "jnats://localhost:4222";
33+
}
34+
35+
natsConnection = initConnection(serverURI);
36+
}
37+
38+
public void closeConnection() {
39+
// Close connection
40+
natsConnection.close();
41+
}
42+
43+
44+
private Connection initConnection(String uri) {
45+
try {
46+
47+
Options options = new Options.Builder()
48+
.errorCb(new ExceptionHandler() {
49+
@Override
50+
public void onException(NATSException ex) {
51+
log.error("Connection Exception: ", ex);
52+
}
53+
})
54+
.disconnectedCb(new DisconnectedCallback() {
55+
@Override
56+
public void onDisconnect(ConnectionEvent event) {
57+
log.error("Channel disconnected: {}", event.getConnection());
58+
}
59+
})
60+
.reconnectedCb(new ReconnectedCallback() {
61+
@Override
62+
public void onReconnect(ConnectionEvent event) {
63+
log.error("Reconnected to server: {}", event.getConnection());
64+
}
65+
})
66+
.build();
67+
68+
return Nats.connect(uri, options);
69+
70+
} catch (IOException ioe) {
71+
log.error("Error connecting to NATs! ", ioe);
72+
return null;
73+
}
74+
}
75+
76+
77+
public void publishMessage(String topic, String replyTo, String message) {
78+
try {
79+
// Simple Publisher
80+
natsConnection.publish(topic, replyTo, message.getBytes());
81+
} catch (IOException ioe) {
82+
log.error("Error publishing message: {} to {} ", message, topic, ioe);
83+
}
84+
}
85+
86+
87+
public void subscribeAsync(String topic) {
88+
89+
// Simple Async Subscriber
90+
AsyncSubscription subscription = natsConnection.subscribe(topic, new MessageHandler() {
91+
@Override
92+
public void onMessage(Message msg) {
93+
log.info("Received message on {}", msg.getSubject());
94+
}
95+
});
96+
97+
if (subscription == null) {
98+
log.error("Error subscribing to {}", topic);
99+
} else {
100+
subscriptions.put(topic, subscription);
101+
}
102+
}
103+
104+
public SyncSubscription subscribeSync(String topic) {
105+
// Simple Sync Subscriber
106+
return natsConnection.subscribe(topic);
107+
}
108+
109+
public void unsubscribe(String topic) {
110+
111+
try {
112+
Subscription subscription = subscriptions.get(topic);
113+
114+
if (subscription != null) {
115+
subscription.unsubscribe();
116+
} else {
117+
log.error("{} not found. Unable to unsubscribe.", topic);
118+
}
119+
120+
} catch (IOException ioe) {
121+
log.error("Error unsubscribing from {} ", topic, ioe);
122+
}
123+
}
124+
125+
126+
public Message makeRequest(String topic, String request) {
127+
128+
try {
129+
return natsConnection.request(topic, request.getBytes(), 100);
130+
} catch (IOException | InterruptedException ioe) {
131+
log.error("Error making request {} to {} ", topic, request, ioe);
132+
return null;
133+
}
134+
}
135+
136+
public void installReply(String topic, String reply) {
137+
natsConnection.subscribe(topic, message -> {
138+
try {
139+
natsConnection.publish(message.getReplyTo(), reply.getBytes());
140+
} catch (Exception e) {
141+
e.printStackTrace();
142+
}
143+
});
144+
}
145+
146+
public SyncSubscription joinQueueGroup(String topic, String queue) {
147+
return natsConnection.subscribe(topic, queue);
148+
}
149+
150+
}
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
package com.baeldung.jnats;
2+
3+
import io.nats.client.Message;
4+
import io.nats.client.SyncSubscription;
5+
import org.junit.Test;
6+
7+
import java.util.ArrayList;
8+
import java.util.List;
9+
10+
import static org.junit.Assert.assertEquals;
11+
import static org.junit.Assert.assertNotNull;
12+
import static org.junit.Assert.assertNull;
13+
14+
public class NatsClientLiveTest {
15+
16+
@Test
17+
public void givenMessageExchange_MessagesReceived() throws Exception {
18+
19+
NatsClient client = connectClient();
20+
21+
SyncSubscription fooSubscription = client.subscribeSync("foo.bar");
22+
SyncSubscription barSubscription = client.subscribeSync("bar.foo");
23+
client.publishMessage("foo.bar", "bar.foo", "hello there");
24+
25+
Message message = fooSubscription.nextMessage(200);
26+
assertNotNull("No message!", message);
27+
assertEquals("hello there", new String(message.getData()));
28+
29+
client.publishMessage(message.getReplyTo(), message.getSubject(), "hello back");
30+
31+
message = barSubscription.nextMessage(200);
32+
assertNotNull("No message!", message);
33+
assertEquals("hello back", new String(message.getData()));
34+
}
35+
36+
37+
private NatsClient connectClient() {
38+
return new NatsClient();
39+
}
40+
41+
@Test
42+
public void whenWildCardSubscription_andMatchTopic_MessageReceived() throws Exception {
43+
44+
NatsClient client = connectClient();
45+
46+
SyncSubscription fooSubscription = client.subscribeSync("foo.*");
47+
48+
client.publishMessage("foo.bar", "bar.foo", "hello there");
49+
50+
Message message = fooSubscription.nextMessage(200);
51+
assertNotNull("No message!", message);
52+
assertEquals("hello there", new String(message.getData()));
53+
}
54+
55+
@Test
56+
public void whenWildCardSubscription_andNotMatchTopic_NoMessageReceived() throws Exception {
57+
58+
NatsClient client = connectClient();
59+
60+
SyncSubscription fooSubscription = client.subscribeSync("foo.*");
61+
62+
client.publishMessage("foo.bar.plop", "bar.foo", "hello there");
63+
64+
Message message = fooSubscription.nextMessage(200);
65+
assertNull("Got message!", message);
66+
67+
68+
SyncSubscription barSubscription = client.subscribeSync("foo.>");
69+
70+
client.publishMessage("foo.bar.plop", "bar.foo", "hello there");
71+
72+
message = barSubscription.nextMessage(200);
73+
assertNotNull("No message!", message);
74+
assertEquals("hello there", new String(message.getData()));
75+
76+
77+
}
78+
79+
80+
@Test
81+
public void givenRequest_ReplyReceived() {
82+
83+
NatsClient client = connectClient();
84+
client.installReply("salary.requests", "denied!");
85+
86+
Message reply = client.makeRequest("salary.requests", "I need a raise.");
87+
assertNotNull("No message!", reply);
88+
assertEquals("denied!", new String(reply.getData()));
89+
90+
}
91+
92+
@Test
93+
public void givenQueueMessage_OnlyOneReceived() throws Exception {
94+
95+
NatsClient client = connectClient();
96+
97+
SyncSubscription queue1 = client.joinQueueGroup("foo.bar.requests", "queue1");
98+
SyncSubscription queue2 = client.joinQueueGroup("foo.bar.requests", "queue1");
99+
100+
client.publishMessage("foo.bar.requests", "queuerequestor", "foobar");
101+
102+
List<Message> messages = new ArrayList<>();
103+
104+
Message message = queue1.nextMessage(200);
105+
106+
if (message != null) messages.add(message);
107+
message = queue2.nextMessage(200);
108+
109+
if (message != null) messages.add(message);
110+
assertEquals(1, messages.size());
111+
112+
}
113+
114+
}

0 commit comments

Comments
 (0)