Java Code Examples for io.nats.client.Connection#flush()

The following examples show how to use io.nats.client.Connection#flush() . 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: NatsBenchmarkDriver.java    From openmessaging-benchmark with Apache License 2.0 6 votes vote down vote up
@Override public CompletableFuture<BenchmarkConsumer> createConsumer(String topic, String subscriptionName,
    ConsumerCallback consumerCallback) {
    Dispatcher natsConsumer;
    Connection cn;
    log.info("createConsumer");
    try {
        Options options = new Options.Builder().server(config.natsHostUrl).maxReconnects(5).build();
        cn = Nats.connect(options);
        natsConsumer = cn.createDispatcher((msg) -> {
            consumerCallback.messageReceived(msg.getData(), Long.parseLong(msg.getReplyTo()));
        });
        natsConsumer.subscribe(topic, subscriptionName);
        cn.flush(Duration.ZERO);
    } catch (Exception e) {
        log.error("createConsumer excetopin " + e);
        return null;
    }
    log.info("createCOnsumer done");
    return CompletableFuture.completedFuture(new NatsBenchmarkConsumer(cn));
}
 
Example 2
Source File: PubBenchmark.java    From nats.java with Apache License 2.0 6 votes vote down vote up
public void execute(Options connectOptions) throws InterruptedException {
    byte[] payload = createPayload();
    String subject = getSubject();

    try {
        Connection nc = Nats.connect(connectOptions);
        try {
            this.startTiming();
            for(int i = 0; i < this.getMessageCount(); i++) {
                nc.publish(subject, payload);
            }
            try {nc.flush(Duration.ofSeconds(5));}catch(Exception e){}
            this.endTiming();
        } finally {
            nc.close();
        }
    } catch (IOException ex) {
        this.setException(ex);
    }
}
 
Example 3
Source File: NatsPub.java    From nats.java with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) {
    String subject;
    String message;
    String server;

    if (args.length == 3) {
        server = args[0];
        subject = args[1];
        message = args[2];
    } else if (args.length == 2) {
        server = Options.DEFAULT_URL;
        subject = args[0];
        message = args[1];
    } else {
        usage();
        return;
    }

    try {
        Connection nc = Nats.connect(ExampleUtils.createExampleOptions(server, false));

        System.out.println();
        System.out.printf("Sending %s on %s, server is %s\n", message, subject, server);
        System.out.println();
        nc.publish(subject, message.getBytes(StandardCharsets.UTF_8));
        nc.flush(Duration.ofSeconds(5));
        nc.close();

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example 4
Source File: ReconnectTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
static void flushAndWait(Connection nc, TestHandler handler) {
    try {
        nc.flush(Duration.ofSeconds(1));
    } catch (Exception exp) {
    }

    handler.waitForStatusChange(15, TimeUnit.SECONDS);
}
 
Example 5
Source File: ErrorListenerTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiscardedMessageServerClosed() throws Exception {
    int maxMessages = 10;
    TestHandler handler = new TestHandler();
    try (NatsTestServer ts = new NatsTestServer(false)) {
        Options options = new Options.Builder().
                server(ts.getURI()).
                maxMessagesInOutgoingQueue(maxMessages).
                discardMessagesWhenOutgoingQueueFull().
                pingInterval(Duration.ofSeconds(100)). // make this long so we don't ping during test
                connectionListener(handler).
                errorListener(handler).
                build();
        Connection nc = Nats.connect(options);
        assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
        try {
            nc.flush(Duration.ofSeconds(1)); // Get the sub to the server

            handler.prepForStatusChange(Events.DISCONNECTED);
            ts.close();
            handler.waitForStatusChange(2, TimeUnit.SECONDS); // make sure the connection is down

            for (int i = 0; i < maxMessages + 1; i++) {
                nc.publish("subject" + i, ("message" + i).getBytes());
            }
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }

    List<Message> discardedMessages = handler.getDiscardedMessages();
    assertTrue("At least one message discarded", discardedMessages.size() >= 1);
    assertTrue("Message subject", discardedMessages.get(0).getSubject().startsWith("subject"));
    assertTrue("Message data", new String(discardedMessages.get(0).getData()).startsWith("message"));
}
 
Example 6
Source File: NatsSub.java    From nats.java with Apache License 2.0 4 votes vote down vote up
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();
    }
}
 
Example 7
Source File: NatsReply.java    From nats.java with Apache License 2.0 4 votes vote down vote up
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 8
Source File: NatsPubMod.java    From nats.java with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) {
    String subject;
    String message;
    String server;

    if (args.length == 3) {
        server = args[0];
        subject = args[1];
        message = args[2];
    } else if (args.length == 2) {
        server = Options.DEFAULT_URL;
        subject = args[0];
        message = args[1];
    } else {
        usage();
        return;
    }

    try {
        Connection nc = Nats.connect(ExampleUtils.createExampleOptions(server, true));

        System.out.println();
        System.out.printf("Sending %s on %s, server is %s\n", message, subject, server);
        System.out.println();


        for (int i = 0; i < 100000; i++) {
            try
            {
                Thread.sleep(500);
                nc.publish(subject, message.getBytes(StandardCharsets.UTF_8));
                nc.flush(Duration.ofSeconds(5));
            }
            catch (Exception e)
            {
                System.out.println("Exception: " + e.getMessage());
            }
        }


        nc.close();

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example 9
Source File: NatsDispatch.java    From nats.java with Apache License 2.0 4 votes vote down vote up
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));
        CountDownLatch latch = new CountDownLatch(msgCount); // dispatcher runs callback in another thread
        
        Dispatcher d = nc.createDispatcher((msg) -> {
            System.out.printf("Received message \"%s\" on subject \"%s\"\n", 
                                    new String(msg.getData(), StandardCharsets.UTF_8), 
                                    msg.getSubject());
            latch.countDown();
        });
        d.subscribe(subject);

        nc.flush(Duration.ZERO);

        latch.await();
        nc.close();
        
    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example 10
Source File: NatsQSub.java    From nats.java with Apache License 2.0 4 votes vote down vote up
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 11
Source File: Stan.java    From nats.java with Apache License 2.0 4 votes vote down vote up
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 12
Source File: ConnectionListenerTests.java    From nats.java with Apache License 2.0 4 votes vote down vote up
@Test
public void testDisconnectReconnectCount() throws Exception {
    Connection nc = null;
    TestHandler handler = new TestHandler();
    try {
        int port;
        try (NatsTestServer ts = new NatsTestServer(false)) {
            Options options = new Options.Builder().
                                server(ts.getURI()).
                                reconnectWait(Duration.ofMillis(100)).
                                maxReconnects(-1).
                                connectionListener(handler).
                                build();
            port = ts.getPort();
            nc = Nats.connect(options);
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
            assertEquals(ts.getURI(), nc.getConnectedUrl());
            handler.prepForStatusChange(Events.DISCONNECTED);
        }

        try {
            nc.flush(Duration.ofMillis(50));
        } catch (Exception exp) {
        }

        handler.waitForStatusChange(400, TimeUnit.MILLISECONDS);

        assertTrue(handler.getEventCount(Events.DISCONNECTED) >= 1);
        assertNull(nc.getConnectedUrl());


        try (NatsTestServer ts = new NatsTestServer(port, false)) {
            try {
                Thread.sleep(200);
            } catch (Exception e) {
            }
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
        
            assertEquals(1, handler.getEventCount(Events.RECONNECTED));
            assertEquals(ts.getURI(), nc.getConnectedUrl());
        }
    } finally {
        nc.close();
        assertNull(nc.getConnectedUrl());
    }
}