use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.
the class TopicsConsumerImpl method doAcknowledge.
@Override
protected CompletableFuture<Void> doAcknowledge(MessageId messageId, AckType ackType, Map<String, Long> properties) {
checkArgument(messageId instanceof TopicMessageIdImpl);
TopicMessageIdImpl messageId1 = (TopicMessageIdImpl) messageId;
if (getState() != State.Ready) {
return FutureUtil.failedFuture(new PulsarClientException("Consumer already closed"));
}
if (ackType == AckType.Cumulative) {
return FutureUtil.failedFuture(new PulsarClientException.NotSupportedException("Cumulative acknowledge not supported for topics consumer"));
} else {
ConsumerImpl<T> consumer = consumers.get(messageId1.getTopicName());
MessageId innerId = messageId1.getInnerMessageId();
return consumer.doAcknowledge(innerId, ackType, properties).thenRun(() -> unAckedMessageTracker.remove(messageId1));
}
}
use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.
the class TopicsConsumerImpl method removeExpiredMessagesFromQueue.
private void removeExpiredMessagesFromQueue(Set<MessageId> messageIds) {
Message<T> peek = incomingMessages.peek();
if (peek != null) {
if (!messageIds.contains(peek.getMessageId())) {
// first message is not expired, then no message is expired in queue.
return;
}
// try not to remove elements that are added while we remove
Message<T> message = incomingMessages.poll();
checkState(message instanceof TopicMessageImpl);
while (message != null) {
MessageId messageId = message.getMessageId();
if (!messageIds.contains(messageId)) {
messageIds.add(messageId);
break;
}
message = incomingMessages.poll();
}
}
}
use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.
the class SampleAsyncProducer method main.
public static void main(String[] args) throws PulsarClientException, InterruptedException, IOException {
PulsarClient pulsarClient = PulsarClient.builder().serviceUrl("http://localhost:8080").build();
Producer<byte[]> producer = pulsarClient.newProducer().topic("persistent://my-property/use/my-ns/my-topic").sendTimeout(3, TimeUnit.SECONDS).create();
List<CompletableFuture<MessageId>> futures = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
final String content = "my-message-" + i;
CompletableFuture<MessageId> future = producer.sendAsync(content.getBytes());
future.handle((v, ex) -> {
if (ex == null) {
log.info("Message persisted: {}", content);
} else {
log.error("Error persisting message: {}", content, ex);
}
return null;
});
futures.add(future);
}
log.info("Waiting for async ops to complete");
for (CompletableFuture<MessageId> future : futures) {
future.join();
}
log.info("All operations completed");
pulsarClient.close();
}
use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.
the class PerformanceReader method main.
public static void main(String[] args) throws Exception {
final Arguments arguments = new Arguments();
JCommander jc = new JCommander(arguments);
jc.setProgramName("pulsar-perf-reader");
try {
jc.parse(args);
} catch (ParameterException e) {
System.out.println(e.getMessage());
jc.usage();
System.exit(-1);
}
if (arguments.help) {
jc.usage();
System.exit(-1);
}
if (arguments.topic.size() != 1) {
System.out.println("Only one topic name is allowed");
jc.usage();
System.exit(-1);
}
if (arguments.confFile != null) {
Properties prop = new Properties(System.getProperties());
prop.load(new FileInputStream(arguments.confFile));
if (arguments.serviceURL == null) {
arguments.serviceURL = prop.getProperty("brokerServiceUrl");
}
if (arguments.serviceURL == null) {
arguments.serviceURL = prop.getProperty("webServiceUrl");
}
// fallback to previous-version serviceUrl property to maintain backward-compatibility
if (arguments.serviceURL == null) {
arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
}
if (arguments.authPluginClassName == null) {
arguments.authPluginClassName = prop.getProperty("authPlugin", null);
}
if (arguments.authParams == null) {
arguments.authParams = prop.getProperty("authParams", null);
}
if (arguments.useTls == false) {
arguments.useTls = Boolean.parseBoolean(prop.getProperty("useTls"));
}
if (isBlank(arguments.tlsTrustCertsFilePath)) {
arguments.tlsTrustCertsFilePath = prop.getProperty("tlsTrustCertsFilePath", "");
}
}
// Dump config variables
ObjectMapper m = new ObjectMapper();
ObjectWriter w = m.writerWithDefaultPrettyPrinter();
log.info("Starting Pulsar performance reader with config: {}", w.writeValueAsString(arguments));
final TopicName prefixTopicName = TopicName.get(arguments.topic.get(0));
final RateLimiter limiter = arguments.rate > 0 ? RateLimiter.create(arguments.rate) : null;
ReaderListener<byte[]> listener = (reader, msg) -> {
messagesReceived.increment();
bytesReceived.add(msg.getData().length);
if (limiter != null) {
limiter.acquire();
}
};
ClientBuilder clientBuilder = //
PulsarClient.builder().serviceUrl(//
arguments.serviceURL).connectionsPerBroker(//
arguments.maxConnections).statsInterval(arguments.statsIntervalSeconds, //
TimeUnit.SECONDS).ioThreads(//
Runtime.getRuntime().availableProcessors()).enableTls(//
arguments.useTls).tlsTrustCertsFilePath(arguments.tlsTrustCertsFilePath);
if (isNotBlank(arguments.authPluginClassName)) {
clientBuilder.authentication(arguments.authPluginClassName, arguments.authParams);
}
PulsarClient pulsarClient = clientBuilder.build();
List<CompletableFuture<Reader<byte[]>>> futures = Lists.newArrayList();
MessageId startMessageId;
if ("earliest".equals(arguments.startMessageId)) {
startMessageId = MessageId.earliest;
} else if ("latest".equals(arguments.startMessageId)) {
startMessageId = MessageId.latest;
} else {
String[] parts = arguments.startMessageId.split(":");
startMessageId = new MessageIdImpl(Long.parseLong(parts[0]), Long.parseLong(parts[1]), -1);
}
ReaderBuilder<byte[]> readerBuilder = //
pulsarClient.newReader().readerListener(//
listener).receiverQueueSize(//
arguments.receiverQueueSize).startMessageId(startMessageId);
for (int i = 0; i < arguments.numTopics; i++) {
final TopicName topicName = (arguments.numTopics == 1) ? prefixTopicName : TopicName.get(String.format("%s-%d", prefixTopicName, i));
futures.add(readerBuilder.clone().topic(topicName.toString()).createAsync());
}
FutureUtil.waitForAll(futures).get();
log.info("Start reading from {} topics", arguments.numTopics);
long oldTime = System.nanoTime();
while (true) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
break;
}
long now = System.nanoTime();
double elapsed = (now - oldTime) / 1e9;
double rate = messagesReceived.sumThenReset() / elapsed;
double throughput = bytesReceived.sumThenReset() / elapsed * 8 / 1024 / 1024;
log.info("Read throughput: {} msg/s -- {} Mbit/s", dec.format(rate), dec.format(throughput));
oldTime = now;
}
pulsarClient.close();
}
use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.
the class ConsumerHandler method onWebSocketText.
@Override
public void onWebSocketText(String message) {
super.onWebSocketText(message);
// We should have received an ack
MessageId msgId;
try {
ConsumerAck ack = ObjectMapperFactory.getThreadLocal().readValue(message, ConsumerAck.class);
msgId = MessageId.fromByteArray(Base64.getDecoder().decode(ack.messageId));
} catch (IOException e) {
log.warn("Failed to deserialize message id: {}", message, e);
close(WebSocketError.FailedToDeserializeFromJSON);
return;
}
consumer.acknowledgeAsync(msgId).thenAccept(consumer -> numMsgsAcked.increment());
int pending = pendingMessages.getAndDecrement();
if (pending >= maxPendingMessages) {
// Resume delivery
receiveMessage();
}
}
Aggregations