io.nats.client.Subscription Java Examples
The following examples show how to use
io.nats.client.Subscription.
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: DataFlowHandler.java From nats-connector-framework with Apache License 2.0 | 6 votes |
public void unsubscribe(String subject) { if (subject == null) return; synchronized (pluginLock) { logger.debug("Plugin unsubscribe from '{}'.", subject); Subscription s = (Subscription) subscriptions.get(subject); if (s == null) { logger.debug("Subscription not found."); return; } try { s.unsubscribe(); } catch (Exception e) { logger.debug("Plugin unsubscribe failed.", e); return; } } }
Example #2
Source File: DataFlowHandler.java From nats-connector-framework with Apache License 2.0 | 6 votes |
public void unsubscribe(String subject) { if (subject == null) return; synchronized (pluginLock) { logger.debug("Plugin unsubscribe from '{}'.", subject); Subscription s = (Subscription) subscriptions.get(subject); if (s == null) { logger.debug("Subscription not found."); return; } try { s.unsubscribe(); } catch (Exception e) { logger.debug("Plugin unsubscribe failed.", e); return; } } }
Example #3
Source File: ErrorListenerTests.java From nats.java with Apache License 2.0 | 6 votes |
@Test public void testExceptionInSlowConsumerHandler() throws Exception { BadHandler handler = new BadHandler(); try (NatsTestServer ts = new NatsTestServer(false); NatsConnection nc = (NatsConnection) Nats.connect(new Options.Builder(). server(ts.getURI()). errorListener(handler). build())) { Subscription sub = nc.subscribe("subject"); sub.setPendingLimits(1, -1); nc.publish("subject", null); nc.publish("subject", null); nc.publish("subject", null); nc.publish("subject", null); nc.flush(Duration.ofMillis(5000)); assertEquals(3, sub.getDroppedCount()); nc.close(); // should force the exception handler through assertTrue(((NatsConnection)nc).getNatsStatistics().getExceptions()>0); } }
Example #4
Source File: NatsConnection.java From nats.java with Apache License 2.0 | 6 votes |
public Subscription subscribe(String subject, String queueName) { if (subject == null || subject.length() == 0) { throw new IllegalArgumentException("Subject is required in subscribe"); } Pattern pattern = Pattern.compile("\\s"); Matcher smatcher = pattern.matcher(subject); if (smatcher.find()) { throw new IllegalArgumentException("Subject cannot contain whitespace"); } if (queueName == null || queueName.length() == 0) { throw new IllegalArgumentException("QueueName is required in subscribe"); } Matcher qmatcher = pattern.matcher(queueName); if (qmatcher.find()) { throw new IllegalArgumentException("Queue names cannot contain whitespace"); } return createSubscription(subject, queueName, null); }
Example #5
Source File: NatsClient.java From tutorials with MIT License | 5 votes |
public void unsubscribe(String topic) { try { Subscription subscription = subscriptions.get(topic); if (subscription != null) { subscription.unsubscribe(); } else { log.error("{} not found. Unable to unsubscribe.", topic); } } catch (IOException ioe) { log.error("Error unsubscribing from {} ", topic, ioe); } }
Example #6
Source File: DispatcherTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalStateException.class) public void testThrowOnWrongSubscription() throws IOException, InterruptedException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { Dispatcher d = nc.createDispatcher((msg) -> {}); Subscription sub2 = nc.subscribe("test"); d.unsubscribe(sub2); assertFalse(true); } }
Example #7
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 #8
Source File: DrainTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testDrainWithZeroTimeout() throws Exception { try (NatsTestServer ts = new NatsTestServer(false); Connection subCon = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build()); Connection pubCon = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build())) { assertTrue("Connected Status", Connection.Status.CONNECTED == subCon.getStatus()); assertTrue("Connected Status", Connection.Status.CONNECTED == pubCon.getStatus()); Subscription sub = subCon.subscribe("draintest"); subCon.flush(Duration.ofSeconds(1)); // Get the sub to the server pubCon.publish("draintest", null); pubCon.publish("draintest", null); // publish 2 pubCon.flush(Duration.ofSeconds(1)); Message msg = sub.nextMessage(Duration.ofSeconds(1)); // read 1 assertNotNull(msg); subCon.flush(Duration.ofSeconds(1)); CompletableFuture<Boolean> tracker = sub.drain(Duration.ZERO); msg = sub.nextMessage(Duration.ofSeconds(1)); // read the second one, should be there because we drained assertNotNull(msg); assertTrue(tracker.get(1, TimeUnit.SECONDS)); assertFalse(sub.isActive()); } }
Example #9
Source File: DrainTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testSimpleSubDrain() throws Exception { try (NatsTestServer ts = new NatsTestServer(false); Connection subCon = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build()); Connection pubCon = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build())) { assertTrue("Connected Status", Connection.Status.CONNECTED == subCon.getStatus()); assertTrue("Connected Status", Connection.Status.CONNECTED == pubCon.getStatus()); Subscription sub = subCon.subscribe("draintest"); subCon.flush(Duration.ofSeconds(1)); // Get the sub to the server pubCon.publish("draintest", null); pubCon.publish("draintest", null); // publish 2 pubCon.flush(Duration.ofSeconds(1)); Message msg = sub.nextMessage(Duration.ofSeconds(1)); // read 1 assertNotNull(msg); subCon.flush(Duration.ofSeconds(1)); CompletableFuture<Boolean> tracker = sub.drain(Duration.ofSeconds(1)); msg = sub.nextMessage(Duration.ofSeconds(1)); // read the second one, should be there because we drained assertNotNull(msg); assertTrue(tracker.get(1, TimeUnit.SECONDS)); assertFalse(sub.isActive()); assertEquals(((NatsConnection) subCon).getConsumerCount(), 0); } }
Example #10
Source File: SlowConsumerTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testSlowSubscriberByBytes() throws Exception { try (NatsTestServer ts = new NatsTestServer(false); NatsConnection nc = (NatsConnection) Nats.connect(ts.getURI())) { Subscription sub = nc.subscribe("subject"); sub.setPendingLimits(-1, 10); // will take the first, not the second assertEquals(10, sub.getPendingByteLimit()); assertEquals(-1, sub.getPendingMessageLimit()); assertEquals(0, sub.getDroppedCount()); nc.publish("subject", null); nc.publish("subject", null); nc.flush(Duration.ofMillis(5000)); assertEquals(1, sub.getDroppedCount()); assertEquals(1, sub.getPendingMessageCount()); assertEquals(19, sub.getPendingByteCount()); // "msg 1 subject 0" + crlf + crlf sub.clearDroppedCount(); nc.publish("subject", null); nc.flush(Duration.ofMillis(5000)); assertEquals(1, sub.getDroppedCount()); assertEquals(1, sub.getPendingMessageCount()); } }
Example #11
Source File: SlowConsumerTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testSlowSubscriberByMessages() throws Exception { try (NatsTestServer ts = new NatsTestServer(false); NatsConnection nc = (NatsConnection) Nats.connect(ts.getURI())) { Subscription sub = nc.subscribe("subject"); sub.setPendingLimits(1, -1); assertEquals(1, sub.getPendingMessageLimit()); assertEquals(-1, sub.getPendingByteLimit()); assertEquals(0, sub.getDroppedCount()); nc.publish("subject", null); nc.publish("subject", null); nc.publish("subject", null); nc.publish("subject", null); nc.flush(Duration.ofMillis(5000)); assertEquals(3, sub.getDroppedCount()); assertEquals(1, sub.getPendingMessageCount()); assertEquals(19, sub.getPendingByteCount()); // "msg 1 subject 0" + crlf + crlf sub.clearDroppedCount(); nc.publish("subject", null); nc.flush(Duration.ofMillis(5000)); assertEquals(1, sub.getDroppedCount()); assertEquals(1, sub.getPendingMessageCount()); } }
Example #12
Source File: SlowConsumerTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testDefaultPendingLimits() throws Exception { try (NatsTestServer ts = new NatsTestServer(false); NatsConnection nc = (NatsConnection) Nats.connect(ts.getURI())) { Subscription sub = nc.subscribe("subject"); Dispatcher d = nc.createDispatcher((Message m) -> {}); assertEquals(sub.getPendingMessageLimit(), Consumer.DEFAULT_MAX_MESSAGES); assertEquals(sub.getPendingByteLimit(), Consumer.DEFAULT_MAX_BYTES); assertEquals(d.getPendingMessageLimit(), Consumer.DEFAULT_MAX_MESSAGES); assertEquals(d.getPendingByteLimit(), Consumer.DEFAULT_MAX_BYTES); } }
Example #13
Source File: NatsDispatcher.java From nats.java with Apache License 2.0 | 5 votes |
public Dispatcher unsubscribe(Subscription subscription, int after) { if (!this.running.get()) { throw new IllegalStateException("Dispatcher is closed"); } if (isDraining()) { // No op while draining return this; } if (subscription.getDispatcher() != this) { throw new IllegalStateException("Subscription is not managed by this Dispatcher"); } // We can probably optimize this path by adding getSID() to the Subscription interface. if (!(subscription instanceof NatsSubscription)) { throw new IllegalArgumentException("This Subscription implementation is not known by Dispatcher"); } NatsSubscription ns = ((NatsSubscription) subscription); // Grab the NatsSubscription to verify we weren't given a different manager's subscription. NatsSubscription sub = this.subscriptionsWithHandlers.get(ns.getSID()); if (sub != null) { this.connection.unsubscribe(sub, after); // Connection will tell us when to remove from the map } return this; }
Example #14
Source File: NatsDispatcher.java From nats.java with Apache License 2.0 | 5 votes |
public Subscription subscribe(String subject, String queueName, MessageHandler handler) { if (subject == null || subject.length() == 0) { throw new IllegalArgumentException("Subject is required in subscribe"); } if (queueName == null || queueName.length() == 0) { throw new IllegalArgumentException("QueueName is required in subscribe"); } if (handler == null) { throw new IllegalArgumentException("MessageHandler is required in subscribe"); } return this.subscribeImpl(subject, queueName, handler); }
Example #15
Source File: NatsDispatcher.java From nats.java with Apache License 2.0 | 5 votes |
public Subscription subscribe(String subject, MessageHandler handler) { if (subject == null || subject.length() == 0) { throw new IllegalArgumentException("Subject is required in subscribe"); } if (handler == null) { throw new IllegalArgumentException("MessageHandler is required in subscribe"); } return this.subscribeImpl(subject, null, handler); }
Example #16
Source File: NatsConnection.java From nats.java with Apache License 2.0 | 5 votes |
public Subscription subscribe(String subject) { if (subject == null || subject.length() == 0) { throw new IllegalArgumentException("Subject is required in subscribe"); } Pattern pattern = Pattern.compile("\\s"); Matcher matcher = pattern.matcher(subject); if (matcher.find()) { throw new IllegalArgumentException("Subject cannot contain whitespace"); } return createSubscription(subject, null, null); }
Example #17
Source File: NatsDispatcher.java From nats.java with Apache License 2.0 | 4 votes |
public Dispatcher unsubscribe(Subscription subscription) { return this.unsubscribe(subscription, -1); }
Example #18
Source File: SlowConsumerTests.java From nats.java with Apache License 2.0 | 4 votes |
@Test public void testSlowSubscriberNotification() throws Exception { TestHandler handler = new TestHandler(); try (NatsTestServer ts = new NatsTestServer(false); NatsConnection nc = (NatsConnection) Nats.connect(new Options.Builder(). server(ts.getURI()).errorListener(handler).build())) { Subscription sub = nc.subscribe("subject"); sub.setPendingLimits(1, -1); Future<Boolean> waitForSlow = handler.waitForSlow(); nc.publish("subject", null); nc.publish("subject", null); nc.publish("subject", null); nc.publish("subject", null); nc.flush(Duration.ofMillis(5000)); // Notification is in another thread, wait for it, or fail waitForSlow.get(1000, TimeUnit.MILLISECONDS); List<Consumer> slow = handler.getSlowConsumers(); assertEquals(1, slow.size()); // should only appear once assertEquals(sub, slow.get(0)); slow.clear(); nc.publish("subject", null); nc.flush(Duration.ofMillis(1000)); assertEquals(0, slow.size()); // no renotifiy waitForSlow = handler.waitForSlow(); // Clear the queue, we shoudl become a non-slow consumer sub.nextMessage(Duration.ofMillis(1000)); // only 1 to get // Notification again on 2nd message nc.publish("subject", null); nc.publish("subject", null); nc.flush(Duration.ofMillis(1000)); waitForSlow.get(1000, TimeUnit.MILLISECONDS); assertEquals(1, slow.size()); // should only appear once assertEquals(sub, slow.get(0)); } }
Example #19
Source File: NatsMessage.java From nats.java with Apache License 2.0 | 4 votes |
public Subscription getSubscription() { return this.subscription; }
Example #20
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 #21
Source File: NatsSubscription.java From nats.java with Apache License 2.0 | 4 votes |
/** * Unsubscribe this subscription and stop listening for messages, after the * specified number of messages. * * <p>If the subscription has already received <code>after</code> messages, it will not receive * more. The provided limit is a lifetime total for the subscription, with the caveat * that if the subscription already received more than <code>after</code> when unsubscribe is called * the client will not travel back in time to stop them.</p> * * <p>For example, to get a single asynchronous message, you might do: * <blockquote><pre> * nc = Nats.connect() * m = nc.subscribe("hello").unsubscribe(1).nextMessage(Duration.ZERO); * </pre></blockquote></p> * * @param after The number of messages to accept before unsubscribing * @return The subscription so that calls can be chained */ public Subscription unsubscribe(int after) { if (this.dispatcher != null) { throw new IllegalStateException( "Subscriptions that belong to a dispatcher cannot respond to unsubscribe directly."); } else if (this.incoming == null) { throw new IllegalStateException("This subscription is inactive."); } if (isDraining()) { // No op while draining return this; } this.connection.unsubscribe(this, after); return this; }
Example #22
Source File: NatsQSub.java From nats.java with Apache License 2.0 | 4 votes |
public static void main(String args[]) { String subject; String queue; int msgCount; String server; if (args.length == 4) { server = args[0]; subject = args[1]; queue = args[2]; msgCount = Integer.parseInt(args[3]); } else if (args.length == 3) { server = Options.DEFAULT_URL; subject = args[0]; queue = args[1]; msgCount = Integer.parseInt(args[2]); } else { usage(); return; } try { Connection nc = Nats.connect(ExampleUtils.createExampleOptions(server, true)); Subscription sub = nc.subscribe(subject, queue); nc.flush(Duration.ofSeconds(5)); System.out.println(); for(int i=0;i<msgCount;i++) { Message msg = sub.nextMessage(Duration.ofHours(1)); System.out.printf("Received message \"%s\" on subject \"%s\"\n", new String(msg.getData(), StandardCharsets.UTF_8), msg.getSubject()); } nc.close(); } catch (Exception exp) { exp.printStackTrace(); } }
Example #23
Source File: NatsSub.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 { System.out.println(); System.out.printf("Trying to connect to %s, and listen to %s for %d messages.\n", server, subject, msgCount); System.out.println(); Connection nc = Nats.connect(ExampleUtils.createExampleOptions(server, true)); Subscription sub = nc.subscribe(subject); nc.flush(Duration.ofSeconds(5)); for(int i=0;i<msgCount;i++) { Message msg = sub.nextMessage(Duration.ofHours(1)); System.out.printf("Received message \"%s\" on subject \"%s\"\n", new String(msg.getData(), StandardCharsets.UTF_8), msg.getSubject()); } nc.close(); } catch (Exception exp) { exp.printStackTrace(); } }