Java Code Examples for io.nats.streaming.NatsStreaming#connect()

The following examples show how to use io.nats.streaming.NatsStreaming#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: NatsStreamingBenchmarkDriver.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) {
    Subscription sub;
    StreamingConnection streamingConnection;
    String clientId = "ConsumerInstance" + getRandomString();
    try {
        streamingConnection = NatsStreaming.connect(clusterId, clientId, optsBuilder.build());
        sub = streamingConnection.subscribe(topic, subscriptionName, new MessageHandler() {
            @Override public void onMessage(Message message) {
                consumerCallback.messageReceived(message.getData(), message.getTimestamp());
            }
        }, subBuilder.build());
    } catch (Exception e) {
        log.warn("nats streaming create consumer exception", e);
        return null;
    }
    return CompletableFuture.completedFuture(new NatsStreamingBenchmarkConsumer(streamingConnection, sub, topic));
}
 
Example 2
Source File: NatsStreamingBenchmarkDriver.java    From openmessaging-benchmark with Apache License 2.0 5 votes vote down vote up
@Override public CompletableFuture<BenchmarkProducer> createProducer(String topic) {
    if (natsStreamingPublisher == null) {
        String clientId = "ProducerInstance" + getRandomString();
        try {
            natsStreamingPublisher = NatsStreaming.connect(clusterId, clientId, optsBuilder.build());
        } catch (Exception e) {
            log.warn("nats streaming create producer exception", e);
            return null;
        }
    }

    return CompletableFuture.completedFuture(new NatsStreamingBenchmarkProducer(natsStreamingPublisher, topic));
}
 
Example 3
Source File: FHIRNotificationNATSPublisher.java    From FHIR with Apache License 2.0 4 votes vote down vote up
/**
 * Performs any required initialization to allow us to publish events to the channel.
 */
private void init(String clusterId, String channelName, String clientId, String servers, Properties tlsProps) {
    log.entering(this.getClass().getName(), "init");

    SSLContext ctx = null;

    try {
        this.channelName = channelName;
        if (log.isLoggable(Level.FINER)) {
            log.finer("ClusterId: " + clusterId);
            log.finer("Channel name: " + channelName);
            log.finer("ClientId: " + clientId);
            log.finer("Servers: " + servers);
        }

        // Make sure that the properties file contains the expected properties.
        if (clusterId == null || channelName == null || clientId == null || servers == null || servers.length() == 0) {
            throw new IllegalStateException("Config property missing from the NATS connection properties.");
        }

        if (Boolean.parseBoolean(tlsProps.getProperty("useTLS"))) {
            // Make sure that the tls properties are set.
            if (tlsProps.getProperty("truststore") == null || tlsProps.getProperty("truststorePass") == null || 
                tlsProps.getProperty("keystore") == null || tlsProps.getProperty("keystorePass") == null) {
                throw new IllegalStateException("TLS config property missing from the NATS connection properties.");
            }

            ctx = createSSLContext(tlsProps);
        }

        // Create the NATS client connection options
        io.nats.client.Options.Builder builder = new io.nats.client.Options.Builder();
        builder.maxReconnects(-1);
        builder.connectionName(channelName);
        builder.servers(servers.split(","));
        if (ctx != null) {
            builder.sslContext(ctx);
        }
        io.nats.client.Options natsOptions = builder.build();

        // Create the NATS connection and the streaming connection
        Connection nc = Nats.connect(natsOptions);
        Options streamingOptions = new Options.Builder().natsConn(nc).build();
        sc = NatsStreaming.connect(clusterId, clientId, streamingOptions);

        // Create the publish callback
        acb = new AckHandler() {
            @Override
            public void onAck(String nuid, Exception ex) {
                log.finer("Received ACK for guid: " + nuid);
                if (ex != null && log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, "Error in server ack for guid " + nuid + ": " + ex.getMessage(), ex);
                }
            }
        };

        // Register this NATS implementation as a "subscriber" with our Notification Service.
        // This means that our "notify" method will be called when the server publishes an event.
        service.subscribe(this);
        log.info("Initialized NATS publisher for channel '" + channelName + "' using servers: '" + servers + "'.");
    } catch (Throwable t) {
        String msg = "Caught exception while initializing NATS publisher.";
        log.log(Level.SEVERE, msg, t);
        throw new IllegalStateException(msg, t);
    } finally {
        log.exiting(this.getClass().getName(), "init");
    }
}
 
Example 4
Source File: Subscriber.java    From stan.java with Apache License 2.0 4 votes vote down vote up
private void run() throws Exception {
    Options opts = null;
    if (url != null) {
        opts = new Options.Builder().natsUrl(url).build();
    }

    final CountDownLatch done = new CountDownLatch(1);
    final CountDownLatch start = new CountDownLatch(1);
    final AtomicInteger delivered = new AtomicInteger(0);


    Thread hook = null;

    try (final StreamingConnection sc = NatsStreaming.connect(clusterId, clientId, opts)) {
        try {
            final Subscription sub = sc.subscribe(subject, qgroup, new MessageHandler() {
                public void onMessage(Message msg) {
                    try {
                        start.await();
                    } catch (InterruptedException e) {
                        /* NOOP */
                    }
                    System.out.printf("[#%d] Received on [%s]: '%s'\n",
                            delivered.incrementAndGet(), msg.getSubject(), msg);
                    if (delivered.get() == count) {
                        done.countDown();
                    }
                }
            }, builder.build());
            hook = new Thread() {
                public void run() {
                    System.err.println("\nCaught CTRL-C, shutting down gracefully...\n");
                    try {
                        if (durable == null || durable.isEmpty() || unsubscribe) {
                            sub.unsubscribe();
                        }
                        sc.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    done.countDown();
                }
            };
            Runtime.getRuntime().addShutdownHook(hook);
            System.out.printf("Listening on [%s], clientID=[%s], qgroup=[%s] durable=[%s]\n",
                    sub.getSubject(), clientId, sub.getQueue(),
                    sub.getOptions().getDurableName());
            start.countDown();
            done.await();
            if (durable == null || durable.isEmpty() || unsubscribe) {
                sub.unsubscribe();
            }
            sc.close();
        } finally {
            Runtime.getRuntime().removeShutdownHook(hook);
        }
    }
}