use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.
the class BatchMessageTest method testBatchAndNonBatchCumulativeAcks.
@Test
public void testBatchAndNonBatchCumulativeAcks() throws Exception {
int numMsgs = 50;
int numMsgsInBatch = numMsgs / 10;
final String topicName = "persistent://prop/use/ns-abc/testBatchAndNonBatchCumulativeAcks";
final String subscriptionName = "bnb-sub-1";
Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName);
consumer.close();
ProducerConfiguration producerConf = new ProducerConfiguration();
producerConf.setBatchingMaxPublishDelay(5000, TimeUnit.MILLISECONDS);
producerConf.setBatchingMaxMessages(numMsgsInBatch);
producerConf.setBatchingEnabled(true);
Producer producer = pulsarClient.createProducer(topicName, producerConf);
// create producer to publish non batch messages
Producer noBatchProducer = pulsarClient.createProducer(topicName);
List<CompletableFuture<MessageId>> sendFutureList = Lists.newArrayList();
for (int i = 0; i < numMsgs / 2; i++) {
byte[] message = ("msg-" + i).getBytes();
Message msg = MessageBuilder.create().setContent(message).build();
sendFutureList.add(producer.sendAsync(msg));
byte[] nobatchmsg = ("nobatch-" + i).getBytes();
msg = MessageBuilder.create().setContent(nobatchmsg).build();
sendFutureList.add(noBatchProducer.sendAsync(msg));
}
FutureUtil.waitForAll(sendFutureList).get();
PersistentTopic topic = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
rolloverPerIntervalStats();
assertTrue(topic.getProducers().values().iterator().next().getStats().msgRateIn > 0.0);
assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), (numMsgs / 2) / numMsgsInBatch + numMsgs / 2);
consumer = pulsarClient.subscribe(topicName, subscriptionName);
Message lastunackedMsg = null;
for (int i = 0; i < numMsgs; i++) {
Message msg = consumer.receive(5, TimeUnit.SECONDS);
assertNotNull(msg);
LOG.info("[{}] got message position{} data {}", subscriptionName, msg.getMessageId(), String.valueOf(msg.getData()));
if (i % 2 == 0) {
lastunackedMsg = msg;
} else {
consumer.acknowledgeCumulative(msg);
LOG.info("[{}] did cumulative ack on position{} ", subscriptionName, msg.getMessageId());
}
}
if (lastunackedMsg != null) {
consumer.acknowledgeCumulative(lastunackedMsg);
}
Thread.sleep(100);
assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), 0);
assertTrue(((ConsumerImpl) consumer).isBatchingAckTrackerEmpty());
consumer.close();
producer.close();
noBatchProducer.close();
}
use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.
the class BatchMessageTest method testSimpleBatchProducerWithFixedBatchSize.
@Test(dataProvider = "codec")
public void testSimpleBatchProducerWithFixedBatchSize(CompressionType compressionType) throws Exception {
int numMsgs = 50;
int numMsgsInBatch = numMsgs / 2;
final String topicName = "persistent://prop/use/ns-abc/testSimpleBatchProducerWithFixedBatchSize";
final String subscriptionName = "sub-1" + compressionType.toString();
Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName);
consumer.close();
ProducerConfiguration producerConf = new ProducerConfiguration();
producerConf.setCompressionType(compressionType);
producerConf.setBatchingMaxPublishDelay(5000, TimeUnit.MILLISECONDS);
producerConf.setBatchingMaxMessages(numMsgsInBatch);
producerConf.setBatchingEnabled(true);
Producer producer = pulsarClient.createProducer(topicName, producerConf);
List<CompletableFuture<MessageId>> sendFutureList = Lists.newArrayList();
for (int i = 0; i < numMsgs; i++) {
byte[] message = ("my-message-" + i).getBytes();
Message msg = MessageBuilder.create().setContent(message).build();
sendFutureList.add(producer.sendAsync(msg));
}
FutureUtil.waitForAll(sendFutureList).get();
PersistentTopic topic = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
rolloverPerIntervalStats();
assertTrue(topic.getProducers().values().iterator().next().getStats().msgRateIn > 0.0);
// we expect 2 messages in the backlog since we sent 50 messages with the batch size set to 25. We have set the
// batch time high enough for it to not affect the number of messages in the batch
assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), 2);
consumer = pulsarClient.subscribe(topicName, subscriptionName);
for (int i = 0; i < numMsgs; i++) {
Message msg = consumer.receive(5, TimeUnit.SECONDS);
assertNotNull(msg);
String receivedMessage = new String(msg.getData());
String expectedMessage = "my-message-" + i;
Assert.assertEquals(receivedMessage, expectedMessage, "Received message " + receivedMessage + " did not match the expected message " + expectedMessage);
}
consumer.close();
producer.close();
}
use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.
the class PersistentTopicTest method setupMLAsyncCallbackMocks.
void setupMLAsyncCallbackMocks() {
ledgerMock = mock(ManagedLedger.class);
cursorMock = mock(ManagedCursor.class);
final CompletableFuture<Void> closeFuture = new CompletableFuture<>();
doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();
doReturn("mockCursor").when(cursorMock).getName();
// doNothing().when(cursorMock).asyncClose(new CloseCallback() {
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
// return closeFuture.get();
return closeFuture.complete(null);
}
}).when(cursorMock).asyncClose(new CloseCallback() {
@Override
public void closeComplete(Object ctx) {
log.info("[{}] Successfully closed cursor ledger", "mockCursor");
closeFuture.complete(null);
}
@Override
public void closeFailed(ManagedLedgerException exception, Object ctx) {
// isFenced.set(false);
log.error("Error closing cursor for subscription", exception);
closeFuture.completeExceptionally(new BrokerServiceException.PersistenceException(exception));
}
}, null);
// call openLedgerComplete with ledgerMock on ML factory asyncOpen
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerComplete(ledgerMock, null);
return null;
}
}).when(mlFactoryMock).asyncOpen(matches(".*success.*"), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
// call openLedgerFailed on ML factory asyncOpen
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerFailed(new ManagedLedgerException("Managed ledger failure"), null);
return null;
}
}).when(mlFactoryMock).asyncOpen(matches(".*fail.*"), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
// call addComplete on ledger asyncAddEntry
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
((AddEntryCallback) invocationOnMock.getArguments()[1]).addComplete(new PositionImpl(1, 1), invocationOnMock.getArguments()[2]);
return null;
}
}).when(ledgerMock).asyncAddEntry(any(ByteBuf.class), any(AddEntryCallback.class), anyObject());
// call openCursorComplete on cursor asyncOpen
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
((OpenCursorCallback) invocationOnMock.getArguments()[1]).openCursorComplete(cursorMock, null);
return null;
}
}).when(ledgerMock).asyncOpenCursor(matches(".*success.*"), any(OpenCursorCallback.class), anyObject());
// call deleteLedgerComplete on ledger asyncDelete
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
((DeleteLedgerCallback) invocationOnMock.getArguments()[0]).deleteLedgerComplete(null);
return null;
}
}).when(ledgerMock).asyncDelete(any(DeleteLedgerCallback.class), anyObject());
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
((DeleteCursorCallback) invocationOnMock.getArguments()[1]).deleteCursorComplete(null);
return null;
}
}).when(ledgerMock).asyncDeleteCursor(matches(".*success.*"), any(DeleteCursorCallback.class), anyObject());
}
use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.
the class PersistentTopicTest method testCreateTopic.
@Test
public void testCreateTopic() throws Exception {
final ManagedLedger ledgerMock = mock(ManagedLedger.class);
doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();
final String topicName = "persistent://prop/use/ns-abc/topic1";
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerComplete(ledgerMock, null);
return null;
}
}).when(mlFactoryMock).asyncOpen(anyString(), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
CompletableFuture<Void> future = brokerService.getTopic(topicName).thenAccept(topic -> {
assertTrue(topic.toString().contains(topicName));
}).exceptionally((t) -> {
fail("should not fail");
return null;
});
// wait for completion
try {
future.get(1, TimeUnit.SECONDS);
} catch (Exception e) {
fail("Should not fail or time out");
}
}
use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.
the class BatchMessageTest method testSimpleBatchProducerConsumer.
@Test(dataProvider = "codec")
public void testSimpleBatchProducerConsumer(CompressionType compressionType) throws Exception {
int numMsgs = 500;
int numMsgsInBatch = numMsgs / 20;
final String topicName = "persistent://prop/use/ns-abc/testSimpleBatchProducerConsumer";
final String subscriptionName = "pc-sub-1" + compressionType.toString();
Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName);
consumer.close();
ProducerConfiguration producerConf = new ProducerConfiguration();
producerConf.setCompressionType(compressionType);
producerConf.setBatchingMaxPublishDelay(5000, TimeUnit.MILLISECONDS);
producerConf.setBatchingMaxMessages(numMsgsInBatch);
producerConf.setBatchingEnabled(true);
Producer producer = pulsarClient.createProducer(topicName, producerConf);
List<CompletableFuture<MessageId>> sendFutureList = Lists.newArrayList();
for (int i = 0; i < numMsgs; i++) {
byte[] message = ("msg-" + i).getBytes();
Message msg = MessageBuilder.create().setContent(message).build();
sendFutureList.add(producer.sendAsync(msg));
}
FutureUtil.waitForAll(sendFutureList).get();
PersistentTopic topic = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
rolloverPerIntervalStats();
assertTrue(topic.getProducers().values().iterator().next().getStats().msgRateIn > 0.0);
assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), numMsgs / numMsgsInBatch);
consumer = pulsarClient.subscribe(topicName, subscriptionName);
Message lastunackedMsg = null;
for (int i = 0; i < numMsgs; i++) {
Message msg = consumer.receive(5, TimeUnit.SECONDS);
assertNotNull(msg);
if (i % 2 == 0) {
consumer.acknowledgeCumulative(msg);
} else {
lastunackedMsg = msg;
}
}
if (lastunackedMsg != null) {
consumer.acknowledgeCumulative(lastunackedMsg);
}
Thread.sleep(100);
assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), 0);
consumer.close();
producer.close();
}
Aggregations