|
| 1 | +// Copyright 2025 The NATS Authors |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at: |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package io.nats.examples.jetstream.simple; |
| 15 | + |
| 16 | +import io.nats.client.*; |
| 17 | +import io.nats.client.api.OrderedConsumerConfiguration; |
| 18 | +import io.nats.client.api.StorageType; |
| 19 | +import io.nats.client.impl.ErrorListenerConsoleImpl; |
| 20 | +import io.nats.examples.jetstream.ResilientPublisher; |
| 21 | + |
| 22 | +import java.io.IOException; |
| 23 | +import java.util.concurrent.CountDownLatch; |
| 24 | +import java.util.concurrent.atomic.AtomicInteger; |
| 25 | +import java.util.concurrent.atomic.AtomicLong; |
| 26 | + |
| 27 | +import static io.nats.examples.jetstream.NatsJsUtils.createOrReplaceStream; |
| 28 | + |
| 29 | +/** |
| 30 | + * This example will demonstrate simplified ordered consumer with a handler |
| 31 | + * To run, start a server and then start the example. |
| 32 | + * To test resiliency, kill the server, wait a couple seconds, then restart it. |
| 33 | + */ |
| 34 | +public class OrderedMessageConsumerExample { |
| 35 | + private static final String STREAM = "ordered-stream"; |
| 36 | + private static final String SUBJECT = "ordered-subject"; |
| 37 | + private static final String CONSUMER_PREFIX = "prefix"; |
| 38 | + private static final String MESSAGE_PREFIX = "ordered"; |
| 39 | + private static final int STOP_COUNT = 1_000_000; |
| 40 | + private static final int REPORT_EVERY = 500; |
| 41 | + |
| 42 | + private static final String SERVER = "nats://localhost:4222"; |
| 43 | + |
| 44 | + public static void main(String[] args) { |
| 45 | + Options options = Options.builder() |
| 46 | + .server(SERVER) |
| 47 | + .errorListener(new ErrorListenerConsoleImpl()) |
| 48 | + .build(); |
| 49 | + try (Connection nc = Nats.connect(options)) { |
| 50 | + JetStreamManagement jsm = nc.jetStreamManagement(); |
| 51 | + createOrReplaceStream(jsm, STREAM, StorageType.File, SUBJECT); // file is important, memory won't survive a restart |
| 52 | + |
| 53 | + System.out.println("Starting publish..."); |
| 54 | + ResilientPublisher publisher = new ResilientPublisher(nc, jsm, STREAM, SUBJECT).basicDataPrefix(MESSAGE_PREFIX).jitter(10); |
| 55 | + Thread pubThread = new Thread(publisher); |
| 56 | + pubThread.start(); |
| 57 | + |
| 58 | + // get stream context, create consumer and get the consumer context |
| 59 | + StreamContext streamContext; |
| 60 | + OrderedConsumerContext orderedConsumerContext; |
| 61 | + try { |
| 62 | + OrderedConsumerConfiguration ocConfig = new OrderedConsumerConfiguration() |
| 63 | + .consumerNamePrefix(CONSUMER_PREFIX) |
| 64 | + .filterSubjects(SUBJECT); |
| 65 | + streamContext = nc.getStreamContext(STREAM); |
| 66 | + orderedConsumerContext = streamContext.createOrderedConsumer(ocConfig); |
| 67 | + } |
| 68 | + catch (JetStreamApiException | IOException e) { |
| 69 | + // JetStreamApiException: |
| 70 | + // the stream or consumer did not exist |
| 71 | + // IOException: |
| 72 | + // likely a connection problem |
| 73 | + return; |
| 74 | + } |
| 75 | + |
| 76 | + CountDownLatch latch = new CountDownLatch(1); |
| 77 | + AtomicInteger atomicCount = new AtomicInteger(); |
| 78 | + AtomicLong nextExpectedSequence = new AtomicLong(0); |
| 79 | + long start = System.nanoTime(); |
| 80 | + MessageHandler handler = msg -> { |
| 81 | + if (msg.metaData().streamSequence() != nextExpectedSequence.incrementAndGet()) { |
| 82 | + System.out.println("MESSAGE RECEIVED OUT OF ORDER!"); |
| 83 | + System.exit(-1); |
| 84 | + } |
| 85 | + msg.ack(); |
| 86 | + int count = atomicCount.incrementAndGet(); |
| 87 | + if (count % REPORT_EVERY == 0) { |
| 88 | + report("Handler", start, count); |
| 89 | + } |
| 90 | + if (count == STOP_COUNT) { |
| 91 | + latch.countDown(); |
| 92 | + } |
| 93 | + }; |
| 94 | + |
| 95 | + // create the consumer then use it |
| 96 | + // the expires option affects 2 things |
| 97 | + // 1. A pull request expiry |
| 98 | + // 2. The heartbeat checking |
| 99 | + // The default expiry is 30 seconds which means the idle heartbeat is 15 seconds. |
| 100 | + // It takes 3 times the heartbeat to trip the alarm, so the subscription does |
| 101 | + // not restart for 45 seconds since the disconnect. |
| 102 | + // If your messages come in slowly this is fine, but if your messages are coming in fast |
| 103 | + // set the expiresIn much lower. Minimum expires is 1 second (1000ms) |
| 104 | + ConsumeOptions consumeOptions = ConsumeOptions.builder() |
| 105 | + .expiresIn(ConsumeOptions.MIN_EXPIRES_MILLS) |
| 106 | + .build(); |
| 107 | + try (MessageConsumer consumer = orderedConsumerContext.consume(consumeOptions, handler)) { |
| 108 | + latch.await(); |
| 109 | + |
| 110 | + // The consumer has at least 1 pull request active. When stop is called, |
| 111 | + // no more pull requests will be made, but messages already requested |
| 112 | + // will still come across the wire to the client. |
| 113 | + System.out.println("Stop the consumer..."); |
| 114 | + consumer.stop(); |
| 115 | + |
| 116 | + // wait until the consumer is finished |
| 117 | + while (!consumer.isFinished()) { |
| 118 | + //noinspection BusyWait |
| 119 | + Thread.sleep(10); |
| 120 | + } |
| 121 | + } |
| 122 | + catch (JetStreamApiException | IOException e) { |
| 123 | + // JetStreamApiException: |
| 124 | + // 1. the stream or consumer did not exist |
| 125 | + // 2. api calls under the covers theoretically this could fail, but practically it won't. |
| 126 | + // IOException: |
| 127 | + // likely a connection problem |
| 128 | + System.err.println("Exception should be handled properly, just exiting here."); |
| 129 | + System.exit(-1); |
| 130 | + } |
| 131 | + catch (Exception e) { |
| 132 | + // this is from the FetchConsumer being AutoCloseable, but should never be called |
| 133 | + // as work inside the close is already guarded by try/catch |
| 134 | + System.err.println("Exception should be handled properly, just exiting here."); |
| 135 | + System.exit(-1); |
| 136 | + } |
| 137 | + |
| 138 | + report("Final", start, atomicCount.get()); |
| 139 | + |
| 140 | + publisher.stop(); // otherwise it will complain when the connection goes away |
| 141 | + pubThread.join(); |
| 142 | + } |
| 143 | + catch (IOException | InterruptedException ioe) { |
| 144 | + // IOException: |
| 145 | + // problem making the connection |
| 146 | + // InterruptedException: |
| 147 | + // thread interruption in the body of the example |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + private static void report(String label, long start, int count) { |
| 152 | + long ms = (System.nanoTime() - start) / 1_000_000; |
| 153 | + System.out.println(label + ": Received " + count + " messages in " + ms + "ms."); |
| 154 | + } |
| 155 | +} |
0 commit comments