Java Code Examples for io.nats.client.Nats#connect()
The following examples show how to use
io.nats.client.Nats#connect() .
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: PingTests.java From nats.java with Apache License 2.0 | 6 votes |
@Test public void testMaxPingsOut() throws Exception { try (NatsServerProtocolMock ts = new NatsServerProtocolMock(ExitAt.NO_EXIT)) { Options options = new Options.Builder(). server(ts.getURI()). pingInterval(Duration.ofSeconds(10)). // Avoid auto pings maxPingsOut(2). maxReconnects(0). build(); NatsConnection nc = (NatsConnection) Nats.connect(options); try { assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); nc.sendPing(); nc.sendPing(); assertNull("No future returned when past max", nc.sendPing()); } finally { nc.close(); } } }
Example 2
Source File: TLSConnectTests.java From nats.java with Apache License 2.0 | 6 votes |
@Test public void testVerifiedTLSConnection() throws Exception { try (NatsTestServer ts = new NatsTestServer("src/test/resources/tlsverify.conf", false)) { SSLContext ctx = TestSSLUtils.createTestSSLContext(); Options options = new Options.Builder(). server(ts.getURI()). maxReconnects(0). sslContext(ctx). build(); Connection nc = Nats.connect(options); try { assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); } finally { nc.close(); assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus()); } } }
Example 3
Source File: PingTests.java From nats.java with Apache License 2.0 | 6 votes |
@Test(expected=TimeoutException.class) public void testFlushTimeout() throws Exception { try (NatsServerProtocolMock ts = new NatsServerProtocolMock(ExitAt.NO_EXIT)) { Options options = new Options.Builder(). server(ts.getURI()). maxReconnects(0). build(); NatsConnection nc = (NatsConnection) Nats.connect(options); try { assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); // fake server so flush will timeout nc.flush(Duration.ofMillis(50)); } finally { nc.close(); } } }
Example 4
Source File: TLSConnectTests.java From nats.java with Apache License 2.0 | 6 votes |
@Test(expected=IOException.class) public void testClientServerCertMismatch() throws Exception { Connection nc = null; try (NatsTestServer ts = new NatsTestServer("src/test/resources/tlsverify.conf", false)) { SSLContext ctx = TestSSLUtils.createEmptySSLContext(); Options options = new Options.Builder(). server(ts.getURI()). maxReconnects(0). sslContext(ctx). build(); try { nc = Nats.connect(options); } finally { if (nc != null) { nc.close(); assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus()); } } } }
Example 5
Source File: ConnectTests.java From stan.java with Apache License 2.0 | 6 votes |
@Test public void testNatsConnNotClosedOnClose() throws Exception { try (NatsStreamingTestServer srv = new NatsStreamingTestServer(clusterName, false)) { try (io.nats.client.Connection nc = Nats.connect(srv.getURI())) { // Pass this NATS connection to NATS Streaming StreamingConnection sc = NatsStreaming.connect(clusterName, clientName, new Options.Builder().natsConn(nc).build()); assertNotNull(sc); // Now close the NATS Streaming connection sc.close(); // Verify that NATS connection is not closed assertFalse("NATS connection should NOT have been closed in Connect", nc.getStatus() == Status.CLOSED); } // nc } // srv }
Example 6
Source File: TLSConnectTests.java From nats.java with Apache License 2.0 | 6 votes |
@Test public void testURISchemeIPTLSConnection() throws Exception { try (NatsTestServer ts = new NatsTestServer("src/test/resources/tlsverify.conf", false)) { Options options = new Options.Builder(). server("tls://127.0.0.1:"+ts.getPort()). sslContext(TestSSLUtils.createTestSSLContext()). // override the custom one maxReconnects(0). build(); Connection nc = Nats.connect(options); try { assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); } finally { nc.close(); assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus()); } } }
Example 7
Source File: ParseTests.java From nats.java with Apache License 2.0 | 6 votes |
@Test(expected=IllegalArgumentException.class) public void testProtocolLineTooLong() throws Exception { try (NatsTestServer ts = new NatsTestServer(false); NatsConnection nc = (NatsConnection) Nats.connect(new Options.Builder(). server(ts.getURI()). maxControlLine(1024). build())) { NatsConnectionReader reader = nc.getReader(); StringBuilder longString = new StringBuilder(); longString.append("INFO "); for (int i=0;i<500;i++ ){ longString.append("helloworld"); } byte[] bytes = longString.toString().getBytes(StandardCharsets.US_ASCII); reader.fakeReadForTest(bytes); reader.gatherOp(bytes.length); reader.gatherProtocol(bytes.length); reader.parseProtocolMessage(); assertFalse(true); } }
Example 8
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 9
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 10
Source File: RequestTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testCleanupTimerWorks() throws IOException, ExecutionException, TimeoutException, InterruptedException { try (NatsTestServer ts = new NatsTestServer(false)) { long cleanupInterval = 50; Options options = new Options.Builder().server(ts.getURI()).requestCleanupInterval(Duration.ofMillis(cleanupInterval)).build(); Connection nc = Nats.connect(options); try { assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); Future<Message> incoming = nc.request("subject", null); incoming.cancel(true); incoming = nc.request("subject", null); incoming.cancel(true); incoming = nc.request("subject", null); incoming.cancel(true); Thread.sleep(2 * cleanupInterval); assertEquals(0, ((NatsStatistics)nc.getStatistics()).getOutstandingRequests()); // Make sure it is still running incoming = nc.request("subject", null); incoming.cancel(true); incoming = nc.request("subject", null); incoming.cancel(true); incoming = nc.request("subject", null); incoming.cancel(true); Thread.sleep(2 * cleanupInterval); assertEquals(0, ((NatsStatistics)nc.getStatistics()).getOutstandingRequests()); } finally { nc.close(); assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus()); } } }
Example 11
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 12
Source File: DrainTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalStateException.class) public void testThrowIfClosing() throws Exception { try (NatsTestServer ts = new NatsTestServer(false); Connection subCon = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build())) { assertTrue("Connected Status", Connection.Status.CONNECTED == subCon.getStatus()); subCon.close(); subCon.drain(Duration.ofSeconds(1)); } }
Example 13
Source File: NatsMessageTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testCustomMaxControlLine() throws Exception { byte[] body = new byte[10]; String subject = "subject"; String replyTo = "reply"; int maxControlLine = 1024; while (subject.length() <= maxControlLine) { subject = subject + subject; } try (NatsTestServer ts = new NatsTestServer()) { Options options = new Options.Builder(). server(ts.getURI()). maxReconnects(0). maxControlLine(maxControlLine). build(); Connection nc = Nats.connect(options); try { assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); nc.publish(subject, replyTo, body); assertFalse(true); } finally { nc.close(); assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus()); } } }
Example 14
Source File: ReconnectTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalStateException.class) public void testOverflowReconnectBuffer() throws Exception { Connection nc = null; TestHandler handler = new TestHandler(); try { try (NatsTestServer ts = new NatsTestServer()) { Options options = new Options.Builder(). server(ts.getURI()). maxReconnects(-1). connectionListener(handler). reconnectBufferSize(4*512). reconnectWait(Duration.ofSeconds(480)). build(); nc = Nats.connect(options); assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); handler.prepForStatusChange(Events.DISCONNECTED); } flushAndWait(nc, handler); checkReconnectingStatus(nc); for (int i=0;i<20;i++) { nc.publish("test", new byte[512]);// Should blow up by the 5th message } assertFalse(true); } finally { if (nc != null) { nc.close(); } } }
Example 15
Source File: ParseTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IOException.class) public void testMissingSubject() throws Exception { try (NatsTestServer ts = new NatsTestServer(false); NatsConnection nc = (NatsConnection) Nats.connect(ts.getURI())) { NatsConnectionReader reader = nc.getReader(); byte[] bytes = ("MSG 1 1\r\n").getBytes(StandardCharsets.US_ASCII); reader.fakeReadForTest(bytes); reader.gatherOp(bytes.length); reader.gatherMessageProtocol(bytes.length); reader.parseProtocolMessage(); assertFalse(true); } }
Example 16
Source File: ReconnectTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test public void testReconnectToSecondServerFromInfo() throws Exception { NatsConnection nc = null; TestHandler handler = new TestHandler(); try (NatsTestServer ts = new NatsTestServer()) { String striped = ts.getURI().substring("nats://".length()); // info doesn't have protocol String customInfo = "{\"server_id\":\"myid\",\"connect_urls\": [\""+striped+"\"]}"; try (NatsServerProtocolMock ts2 = new NatsServerProtocolMock(null, customInfo)) { Options options = new Options.Builder(). server(ts2.getURI()). connectionListener(handler). maxReconnects(-1). connectionTimeout(Duration.ofSeconds(5)). reconnectWait(Duration.ofSeconds(1)). build(); nc = (NatsConnection) Nats.connect(options); assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); assertEquals(nc.getConnectedUrl(), ts2.getURI()); handler.prepForStatusChange(Events.RECONNECTED); } flushAndWait(nc, handler); assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); assertTrue(ts.getURI().endsWith(nc.getConnectedUrl())); } finally { if (nc != null) { nc.close(); assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus()); } } }
Example 17
Source File: StanTime.java From nats.java with Apache License 2.0 | 5 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 { Options options = new Options.Builder().server(server).noReconnect().build(); Connection nc = Nats.connect(options); Future<Message> replyFuture = nc.request("stan.time", null); Message reply = replyFuture.get(); System.out.printf("The time where stan is, is \"%s\"\n", new String(reply.getData(), StandardCharsets.UTF_8)); 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 testAutoUnsub() throws IOException, InterruptedException, ExecutionException, TimeoutException { try (NatsTestServer ts = new NatsTestServer(false); Connection nc = Nats.connect(ts.getURI())) { final CompletableFuture<Boolean> phase1 = new CompletableFuture<>(); final CompletableFuture<Boolean> phase2 = new CompletableFuture<>(); int msgCount = 100; assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus()); final ConcurrentLinkedQueue<Message> q = new ConcurrentLinkedQueue<>(); NatsDispatcher d = (NatsDispatcher) nc.createDispatcher((msg) -> { if (msg.getSubject().equals("phase1")) { phase1.complete(Boolean.TRUE); }else if (msg.getSubject().equals("phase2")) { phase2.complete(Boolean.TRUE); } else { q.add(msg); } }); d.subscribe("subject"); d.subscribe("phase1"); d.subscribe("phase2"); nc.flush(Duration.ofMillis(500));// Get them all to the server for (int i = 0; i < msgCount; i++) { nc.publish("subject", new byte[16]); } nc.publish("phase1", new byte[16]); nc.flush(Duration.ofMillis(1000)); // wait for them to go through phase1.get(1000, TimeUnit.MILLISECONDS); // make sure we got them assertEquals(msgCount, q.size()); d.unsubscribe("subject", msgCount + 1); for (int i = 0; i < msgCount; i++) { nc.publish("subject", new byte[16]); } nc.publish("phase2", new byte[16]); nc.flush(Duration.ofMillis(1000)); // Wait for it all to get processed phase2.get(1000, TimeUnit.MILLISECONDS); // make sure we got them assertEquals(msgCount + 1, q.size()); } }
Example 19
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 20
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)); } }