|
| 1 | +package com.github.brainlag.nsq; |
| 2 | + |
| 3 | +import com.github.brainlag.nsq.exceptions.NSQException; |
| 4 | +import com.github.brainlag.nsq.lookup.DefaultNSQLookup; |
| 5 | +import com.github.brainlag.nsq.lookup.NSQLookup; |
| 6 | +import org.apache.logging.log4j.LogManager; |
| 7 | +import org.junit.Test; |
| 8 | + |
| 9 | +import java.util.concurrent.TimeoutException; |
| 10 | +import java.util.concurrent.atomic.AtomicInteger; |
| 11 | + |
| 12 | +import static org.junit.Assert.assertTrue; |
| 13 | + |
| 14 | +public class NSQConsumerTest { |
| 15 | + |
| 16 | + //duration to wait before auto-requeing a message setting in nsqd, defined with -msg-timeout: |
| 17 | + //Set your timeout -msg-timeout="5s" command line when starting nsqd or changed this constant |
| 18 | + //to the default of 60000. |
| 19 | + private static final long NSQ_MSG_TIMEOUT = 5000; |
| 20 | + |
| 21 | + @Test |
| 22 | + public void testLongRunningConsumer() throws NSQException, TimeoutException, InterruptedException { |
| 23 | + AtomicInteger counter = new AtomicInteger(0); |
| 24 | + NSQLookup lookup = new DefaultNSQLookup(); |
| 25 | + lookup.addLookupAddress("localhost", 4161); |
| 26 | + |
| 27 | + NSQConsumer consumer = new NSQConsumer(lookup, "test1", "testconsumer", (message) -> { |
| 28 | + LogManager.getLogger(this).info("Processing message: " + new String(message.getMessage())); |
| 29 | + counter.incrementAndGet(); |
| 30 | + |
| 31 | + long sleepTime = NSQ_MSG_TIMEOUT / 5; |
| 32 | + for (int i = 0; i < 5; i++) { |
| 33 | + try { |
| 34 | + Thread.sleep(sleepTime + 500); |
| 35 | + } catch (InterruptedException e) { |
| 36 | + e.printStackTrace(); |
| 37 | + } |
| 38 | + message.touch(); |
| 39 | + } |
| 40 | + message.finished(); |
| 41 | + assertTrue(message.getAttempts() == 1); |
| 42 | + }); |
| 43 | + consumer.start(); |
| 44 | + |
| 45 | + NSQProducer producer = new NSQProducer(); |
| 46 | + producer.addAddress("localhost", 4150); |
| 47 | + producer.start(); |
| 48 | + String msg = "test-one-message"; |
| 49 | + producer.produce("test1", msg.getBytes()); |
| 50 | + producer.shutdown(); |
| 51 | + |
| 52 | + Thread.sleep(NSQ_MSG_TIMEOUT * 2); |
| 53 | + assertTrue(counter.get() == 1); |
| 54 | + consumer.shutdown(); |
| 55 | + } |
| 56 | + |
| 57 | + |
| 58 | +} |
0 commit comments