Skip to content

Commit

Permalink
[Java] Iterating Over Multiple Subscriptions (#253)
Browse files Browse the repository at this point in the history
Signed-off-by: Maurice van Veen <github@mauricevanveen.com>
  • Loading branch information
MauriceVanVeen authored Aug 8, 2024
1 parent 5e17836 commit a78211d
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions examples/messaging/iterating-multiple-subscriptions/java/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package example;

import io.nats.client.Connection;
import io.nats.client.Dispatcher;
import io.nats.client.Nats;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

public class Main {
public static void main(String[] args) {
String natsURL = System.getenv("NATS_URL");
if (natsURL == null) {
natsURL = "nats://127.0.0.1:4222";
}

// Initialize a connection to the server. The connection is AutoCloseable
// on exit.
try (Connection nc = Nats.connect(natsURL)) {

int total = 80;
CountDownLatch latch = new CountDownLatch(total);

// Create a message dispatcher. A dispatcher is a process that runs on
// its own thread, receives incoming messages via a FIFO queue,
// for subjects registered on it. For each message it takes from
// the queue, it makes a blocking call to the MessageHandler
// passed to the createDispatcher call.
Dispatcher dispatcher = nc.createDispatcher((msg) -> {
System.out.printf("Received %s: %s\n",
msg.getSubject(),
new String(msg.getData(), StandardCharsets.UTF_8));
latch.countDown();
});

// Subscribe directly on the dispatcher for multiple subjects.
dispatcher.subscribe("s1");
dispatcher.subscribe("s2");
dispatcher.subscribe("s3");
dispatcher.subscribe("s4");

for (int i = 0; i < total / 4; i++) {
nc.publish("s1", String.valueOf(i).getBytes(StandardCharsets.UTF_8));
nc.publish("s2", String.valueOf(i).getBytes(StandardCharsets.UTF_8));
nc.publish("s3", String.valueOf(i).getBytes(StandardCharsets.UTF_8));
nc.publish("s4", String.valueOf(i).getBytes(StandardCharsets.UTF_8));
Thread.sleep(100);
}

// Await the dispatcher thread to have received all the messages before the program quits.
latch.await();

} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}

1 comment on commit a78211d

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deploy preview for nats-by-example ready!

✅ Preview
https://nats-by-example-86e66d7p0-connecteverything.vercel.app

Built with commit a78211d.
This pull request is being automatically deployed with vercel-action

Please # to comment.