Java Code Examples for io.nats.client.Dispatcher#subscribe()
The following examples show how to use
io.nats.client.Dispatcher#subscribe() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testThrowOnEmptyQueueWithMessageHandler() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe("subject", "", (msg) -> {}); assertFalse(true); } }
Example 2
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testThrowOnEmptyQueue() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe("subject", ""); assertFalse(true); } }
Example 3
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testThrowOnEmptySubject() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe(""); assertFalse(true); } }
Example 4
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testThrowOnNullSubjectWithQueueWithMessageHandler() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe(null, "quque", (msg) -> {}); assertFalse(true); } }
Example 5
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testCloseFromCallback() throws IOException, InterruptedException, ExecutionException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { final CompletableFuture<Boolean> done = new CompletableFuture<>(); assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); final Dispatcher d = nc.createDispatcher((msg) -> { try { if (msg.getSubject().equals("done")) { nc.close(); done.complete(Boolean.TRUE); } } catch (InterruptedException e) { e.printStackTrace(); } }); d.subscribe("done"); nc.flush(Duration.ofMillis(5000));// Get them all to the server nc.publish("done", new byte[16]); // when we get this we know the others are dispatched nc.flush(Duration.ofMillis(5000)); // Wait for the publish done.get(5000, TimeUnit.MILLISECONDS); // make sure we got them assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus()); } }
Example 6
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testThrowOnEmptySubjectWithQueue() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe("", "quque"); assertFalse(true); } }
Example 7
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testUnsubFromCallback() throws IOException, InterruptedException, ExecutionException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { final CompletableFuture<Boolean> done = new CompletableFuture<>(); assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); final AtomicReference<Dispatcher> dispatcher = new AtomicReference<>(); final ConcurrentLinkedQueue<Message> q = new ConcurrentLinkedQueue<>(); final Dispatcher d = nc.createDispatcher((msg) -> { if (msg.getSubject().equals("done")) { done.complete(Boolean.TRUE); } else { q.add(msg); dispatcher.get().unsubscribe("subject"); } }); dispatcher.set(d); d.subscribe("subject"); d.subscribe("done"); nc.flush(Duration.ofMillis(500));// Get them all to the server nc.publish("subject", new byte[16]); nc.publish("subject", new byte[16]); nc.publish("done", new byte[16]); // when we get this we know the others are dispatched nc.flush(Duration.ofMillis(1000)); // Wait for the publish, or we will get multiples for sure done.get(200, TimeUnit.MILLISECONDS); // make sure we got them assertEquals(1, q.size()); } }
Example 8
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testDoubleSubscribeWithCustomHandler() throws IOException, InterruptedException, ExecutionException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { final CompletableFuture<Boolean> done = new CompletableFuture<>(); int msgCount = 100; assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); final AtomicInteger count = new AtomicInteger(0); Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe("subject", (msg) -> { count.incrementAndGet(); }); d.subscribe("subject", "queue", (msg) -> { count.incrementAndGet(); }); d.subscribe("done", (msg) -> { done.complete(Boolean.TRUE); }); nc.flush(Duration.ofSeconds(5)); // wait for them to go through for (int i = 0; i < msgCount; i++) { nc.publish("subject", new byte[16]); } nc.publish("done", new byte[16]); nc.flush(Duration.ofSeconds(5)); // wait for them to go through done.get(5, TimeUnit.SECONDS); assertEquals(msgCount * 2, count.get()); // We should get 2x the messages because we subscribed 2 times. } }
Example 9
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testThrowOnEmptySubjectWithQueueWithMessageHandler() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe("", "quque", (msg) -> {}); assertFalse(true); } }
Example 10
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testThrowOnNullSubjectWithQueue() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe(null, "quque"); assertFalse(true); } }
Example 11
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testThrowOnNullHandlerWithQueue() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe("test", "queue", (MessageHandler)null); assertFalse(true); } }
Example 12
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalStateException.class) public void testThrowOnUnsubWhenClosed() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); Subscription sub = d.subscribe("subject", (msg) -> {}); nc.closeDispatcher(d); d.unsubscribe(sub); assertFalse(true); } }
Example 13
Source File: SlowConsumerTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testSlowSDispatcherByMessages() throws Exception { try (NatsTestServer ts = new NatsTestServer(false); NatsConnection nc = (NatsConnection) Nats.connect(ts.getURI())) { final CompletableFuture<Void> ok = new CompletableFuture<>(); Dispatcher d = nc.createDispatcher((msg) -> { ok.complete(null); Thread.sleep(5 * 60 * 1000); // will wait until interrupted }); d.setPendingLimits(1, -1); d.subscribe("subject"); assertEquals(1, d.getPendingMessageLimit()); assertEquals(-1, d.getPendingByteLimit()); assertEquals(0, d.getDroppedCount()); nc.publish("subject", null); ok.get(1000,TimeUnit.MILLISECONDS); // make sure we got the first one nc.publish("subject", null); nc.publish("subject", null); nc.flush(Duration.ofMillis(1000)); assertEquals(1, d.getDroppedCount()); assertEquals(1, d.getPendingMessageCount()); assertEquals(19, d.getPendingByteCount()); // "msg 1 subject 0" + crlf + crlf d.clearDroppedCount(); nc.publish("subject", null); nc.flush(Duration.ofMillis(5000)); assertEquals(1, d.getDroppedCount()); assertEquals(1, d.getPendingMessageCount()); } }
Example 14
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalStateException.class) public void testThrowOnUnsubscribeWhenClosed() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); d.subscribe("foo"); nc.closeDispatcher(d); d.unsubscribe("foo"); assertFalse(true); } }
Example 15
Source File: PingTests.java From nats.java with Apache License 2.0 | 4 votes |
@Test public void testMessagesDelayPings() throws IOException, InterruptedException, ExecutionException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false)) { Options options = new Options.Builder().server(ts.getURI()). pingInterval(Duration.ofMillis(200)).build(); NatsConnection nc = (NatsConnection) Nats.connect(options); NatsStatistics stats = nc.getNatsStatistics(); try { final CompletableFuture<Boolean> done = new CompletableFuture<>(); assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); Dispatcher d = nc.createDispatcher((msg) -> { if (msg.getSubject().equals("done")) { done.complete(Boolean.TRUE); } }); d.subscribe("subject"); d.subscribe("done"); nc.flush(Duration.ofMillis(1000)); // wait for them to go through long b4 = stats.getPings(); for (int i=0;i<10;i++) { Thread.sleep(50); nc.publish("subject", new byte[16]); } long after = stats.getPings(); assertTrue("pings hidden", after == b4); nc.publish("done", new byte[16]); nc.flush(Duration.ofMillis(1000)); // wait for them to go through done.get(500, TimeUnit.MILLISECONDS); // no more messages, pings should start to go through b4 = stats.getPings(); Thread.sleep(500); after = stats.getPings(); assertTrue("pings restarted", after > b4); } finally { nc.close(); } } }
Example 16
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 4 votes |
@Test public void testQueueSubscribers() throws IOException, InterruptedException, ExecutionException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { int msgs = 100; AtomicInteger received = new AtomicInteger(); AtomicInteger sub1Count = new AtomicInteger(); AtomicInteger sub2Count = new AtomicInteger(); final CompletableFuture<Boolean> done1 = new CompletableFuture<>(); final CompletableFuture<Boolean> done2 = new CompletableFuture<>(); assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); Dispatcher d1 = nc.createDispatcher((msg) -> { if (msg.getSubject().equals("done")) { done1.complete(Boolean.TRUE); } else { sub1Count.incrementAndGet(); received.incrementAndGet(); } }); Dispatcher d2 = nc.createDispatcher((msg) -> { if (msg.getSubject().equals("done")) { done2.complete(Boolean.TRUE); } else { sub2Count.incrementAndGet(); received.incrementAndGet(); } }); d1.subscribe("subject", "queue"); d2.subscribe("subject", "queue"); d1.subscribe("done"); d2.subscribe("done"); nc.flush(Duration.ofMillis(500)); for (int i = 0; i < msgs; i++) { nc.publish("subject", new byte[16]); } nc.publish("done", null); nc.flush(Duration.ofMillis(500)); done1.get(500, TimeUnit.MILLISECONDS); done2.get(500, TimeUnit.MILLISECONDS); assertEquals(msgs, received.get()); assertEquals(msgs, sub1Count.get() + sub2Count.get()); // They won't be equal but print to make sure they are close (human testing) System.out.println("### Sub 1 " + sub1Count.get()); System.out.println("### Sub 2 " + sub2Count.get()); } }
Example 17
Source File: Stan.java From nats.java with Apache License 2.0 | 4 votes |
public static void main(String args[]) { String server = "help"; if (args.length == 1) { server = args[0]; } else if (args.length == 0) { server = Options.DEFAULT_URL; } if (server.equals("help")) { usage(); return; } try { SecureRandom random = new SecureRandom(); CompletableFuture<Void> latch = new CompletableFuture<>(); Options options = new Options.Builder().server(server).noReconnect().build(); Connection nc = Nats.connect(options); Dispatcher d = nc.createDispatcher((msg) -> { String reply = ""; boolean exit = false; switch (msg.getSubject()) { case "stan.time": reply = LocalTime.now().toString(); break; case "stan.random": reply = String.valueOf(random.nextInt()); break; case "stan.exit": if ("confirm".equals(new String(msg.getData(), StandardCharsets.UTF_8))) { reply = "exiting"; exit = true; } else { reply = "you have to confirm the exit"; } break; } nc.publish(msg.getReplyTo(), reply.getBytes(StandardCharsets.UTF_8)); if (exit) { try { nc.flush(Duration.ZERO); latch.complete(null); } catch (TimeoutException e) { e.printStackTrace(); } } }); d.subscribe("stan.time"); d.subscribe("stan.random"); d.subscribe("stan.exit"); nc.flush(Duration.ZERO); System.out.println("Stan is listening..."); latch.get(); System.out.println("Stan is exiting ..."); nc.close(); } catch (Exception exp) { exp.printStackTrace(); } }
Example 18
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 4 votes |
@Test public void testDoubleSubscribeWithUnsubscribeAfterWithCustomHandler() throws IOException, InterruptedException, ExecutionException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { final CompletableFuture<Boolean> done1 = new CompletableFuture<>(); final CompletableFuture<Boolean> done2 = new CompletableFuture<>(); int msgCount = 100; assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); final AtomicInteger count = new AtomicInteger(0); Dispatcher d = nc.createDispatcher((msg) -> {}); Subscription s1 = d.subscribe("subject", (msg) -> { count.incrementAndGet(); }); Subscription doneSub = d.subscribe("done", (msg) -> { done1.complete(Boolean.TRUE); }); d.subscribe("subject", (msg) -> { count.incrementAndGet(); }); nc.flush(Duration.ofSeconds(5)); // wait for the subs to go through for (int i = 0; i < msgCount; i++) { nc.publish("subject", new byte[16]); } nc.publish("done", new byte[16]); nc.flush(Duration.ofSeconds(5)); // wait for the messages to go through done1.get(5, TimeUnit.SECONDS); assertEquals(msgCount * 2, count.get()); // We should get 2x the messages because we subscribed 2 times. count.set(0); d.unsubscribe(s1); d.unsubscribe(doneSub); d.subscribe("done", (msg) -> { done2.complete(Boolean.TRUE); }); nc.flush(Duration.ofSeconds(5)); // wait for the unsub to go through for (int i = 0; i < msgCount; i++) { nc.publish("subject", new byte[16]); } nc.publish("done", new byte[16]); nc.flush(Duration.ofSeconds(5)); // wait for the messages to go through done2.get(5, TimeUnit.SECONDS); assertEquals(msgCount, count.get()); // We only have 1 active subscription, so we should only get msgCount. } }
Example 19
Source File: NatsReply.java From nats.java with Apache License 2.0 | 4 votes |
public static void main(String args[]) { String subject; int msgCount; String server; if (args.length == 3) { server = args[0]; subject = args[1]; msgCount = Integer.parseInt(args[2]); } else if (args.length == 2) { server = Options.DEFAULT_URL; subject = args[0]; msgCount = Integer.parseInt(args[1]); } else { usage(); return; } try { Connection nc = Nats.connect(ExampleUtils.createExampleOptions(server, true)); CountDownLatch latch = new CountDownLatch(msgCount); // dispatcher runs callback in another thread System.out.println(); Dispatcher d = nc.createDispatcher((msg) -> { System.out.printf("Received message \"%s\" on subject \"%s\", replying to %s\n", new String(msg.getData(), StandardCharsets.UTF_8), msg.getSubject(), msg.getReplyTo()); nc.publish(msg.getReplyTo(), msg.getData()); latch.countDown(); }); d.subscribe(subject); nc.flush(Duration.ofSeconds(5)); latch.await(); nc.closeDispatcher(d); // This isn't required, closing the connection will do it nc.close(); } catch (Exception exp) { exp.printStackTrace(); } }
Example 20
Source File: StreamingConnectionImpl.java From stan.java with Apache License 2.0 | 4 votes |
@Override public Subscription subscribe(String subject, String queue, io.nats.streaming.MessageHandler cb, SubscriptionOptions opts) throws IOException, InterruptedException, TimeoutException { SubscriptionImpl sub; io.nats.client.Connection nc; if (opts == null) { opts = new SubscriptionOptions.Builder().build(); } this.lock(); try { if (getNatsConnection() == null) { throw new IllegalStateException(NatsStreaming.ERR_CONNECTION_CLOSED); } sub = createSubscription(subject, queue, cb, this, opts); // Register subscription. subMap.put(sub.inbox, sub); nc = getNatsConnection(); } finally { this.unlock(); } // Hold lock throughout. sub.wLock(); try { Dispatcher d = this.getDispatcherByName(opts.getDispatcherName()); // Listen for actual messages d.subscribe(sub.inbox); // Create a subscription request // FIXME(dlc) add others. SubscriptionRequest sr = createSubscriptionRequest(sub); Message reply = nc.request(subRequests, sr.toByteArray(), opts.getSubscriptionTimeout()); if (reply == null) { d.unsubscribe(sub.inbox); throw new IOException(ERR_SUB_REQ_TIMEOUT); } SubscriptionResponse response; try { response = SubscriptionResponse.parseFrom(reply.getData()); } catch (InvalidProtocolBufferException e) { d.unsubscribe(sub.inbox); throw e; } if (!response.getError().isEmpty()) { d.unsubscribe(sub.inbox); throw new IOException(response.getError()); } sub.setAckInbox(response.getAckInbox()); } finally { sub.wUnlock(); } return sub; }