|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +package io.streamnative.examples.transaction; |
| 19 | + |
| 20 | +import com.beust.jcommander.JCommander; |
| 21 | + |
| 22 | +import java.net.URL; |
| 23 | +import java.util.ArrayList; |
| 24 | +import java.util.List; |
| 25 | +import java.util.concurrent.CompletableFuture; |
| 26 | +import java.util.concurrent.TimeUnit; |
| 27 | +import org.apache.pulsar.client.api.Consumer; |
| 28 | +import org.apache.pulsar.client.api.Message; |
| 29 | +import org.apache.pulsar.client.api.Producer; |
| 30 | +import org.apache.pulsar.client.api.ProducerBuilder; |
| 31 | +import org.apache.pulsar.client.api.PulsarClient; |
| 32 | +import org.apache.pulsar.client.api.PulsarClientException; |
| 33 | +import org.apache.pulsar.client.api.Schema; |
| 34 | +import org.apache.pulsar.client.api.transaction.TransactionCoordinatorClientException; |
| 35 | +import org.apache.pulsar.client.impl.auth.oauth2.AuthenticationFactoryOAuth2; |
| 36 | +import org.apache.pulsar.common.util.FutureUtil; |
| 37 | +import org.slf4j.Logger; |
| 38 | +import org.slf4j.LoggerFactory; |
| 39 | + |
| 40 | +public class TransactionAsyncExample { |
| 41 | + private static final Logger log = LoggerFactory.getLogger(TransactionAsyncExample.class); |
| 42 | + public static void main(String[] args) throws Exception { |
| 43 | + JCommanderPulsar jct = new JCommanderPulsar(); |
| 44 | + JCommander jCommander = new JCommander(jct, args); |
| 45 | + if (jct.help) { |
| 46 | + jCommander.usage(); |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + String topic1 = "persistent://public/default/topic-1"; |
| 51 | + String topic2 = "persistent://public/default/topic-2"; |
| 52 | + |
| 53 | + PulsarClient client = PulsarClient.builder() |
| 54 | + .enableTransaction(true) |
| 55 | + .serviceUrl(jct.serviceUrl) |
| 56 | + .authentication( |
| 57 | + AuthenticationFactoryOAuth2.clientCredentials(new URL(jct.issuerUrl), new URL(jct.credentialsUrl), jct.audience)) |
| 58 | + .build(); |
| 59 | + |
| 60 | + ProducerBuilder<String> producerBuilder = client.newProducer(Schema.STRING).enableBatching(false); |
| 61 | + Producer<String> producer1 = producerBuilder.topic(topic1).sendTimeout(0, TimeUnit.SECONDS).create(); |
| 62 | + Producer<String> producer2 = producerBuilder.topic(topic2).sendTimeout(0, TimeUnit.SECONDS).create(); |
| 63 | + |
| 64 | + Consumer<String> consumer1 = client.newConsumer(Schema.STRING).subscriptionName("test").topic(topic1).subscribe(); |
| 65 | + Consumer<String> consumer2 = client.newConsumer(Schema.STRING).subscriptionName("test").topic(topic2).subscribe(); |
| 66 | + |
| 67 | + int count = 2; |
| 68 | + // First prepare two messages that can be consumed |
| 69 | + for (int i = 0; i < count; i++) { |
| 70 | + producer1.send("Hello Pulsar! count : " + i); |
| 71 | + } |
| 72 | + |
| 73 | + for (int i = 0; i < count; i++) { |
| 74 | + // Consume two messages and send two messages to topic-2 with the same transaction |
| 75 | + // Receive the message first, and then start the transaction after receiving the message. |
| 76 | + // If the transaction is started first and no message is received for |
| 77 | + // a long time, it will cause the transaction to time out. |
| 78 | + final int number = i; |
| 79 | + consumer1.receiveAsync().thenAccept(message -> { |
| 80 | + // receive message success then new transaction |
| 81 | + try { |
| 82 | + client.newTransaction().withTransactionTimeout(10, TimeUnit.SECONDS).build().thenAccept(txn -> { |
| 83 | + // new transaction success, then you can do you own op |
| 84 | + List<CompletableFuture<?>> futures = new ArrayList<>(); |
| 85 | + // add send message with txn future to futures |
| 86 | + futures.add(producer2.newMessage(txn).value("Hello Pulsar! count : " + number).sendAsync()); |
| 87 | + // add ack message with txn future to futures |
| 88 | + futures.add(consumer1.acknowledgeAsync(message.getMessageId(), txn).exceptionally(e -> { |
| 89 | + if (!(e.getCause() instanceof PulsarClientException.TransactionConflictException)) { |
| 90 | + // if not TransactionConflictException, |
| 91 | + // we should redeliver or negativeAcknowledge this message |
| 92 | + // if you don't redeliver or negativeAcknowledge, the message will not receive again |
| 93 | + // ((ConsumerImpl<String>)consumer1).redeliverUnacknowledgedMessages(Collections.singleton(message.getMessageId())); |
| 94 | + // ((MultiTopicsConsumerImpl<String>)consumer1).redeliverUnacknowledgedMessages(Collections.singleton(message.getMessageId())); |
| 95 | + consumer1.negativeAcknowledge(message); |
| 96 | + } |
| 97 | + return null; |
| 98 | + })); |
| 99 | + |
| 100 | + FutureUtil.waitForAll(futures).thenRun(() -> { |
| 101 | + // futures are all success, then can commit this transaction |
| 102 | + txn.commit().thenRun(() -> { |
| 103 | + log.info("txn : {} commit success!", txn); |
| 104 | + }).exceptionally(e -> { |
| 105 | + log.error("txn : {} commit fail!", txn); |
| 106 | + // if not TransactionNotFoundException, you can commit again or abort. also you can wait txn timeout |
| 107 | + if (!(e.getCause() instanceof TransactionCoordinatorClientException.TransactionNotFoundException)) { |
| 108 | + txn.commit(); |
| 109 | + } |
| 110 | + return null; |
| 111 | + }); |
| 112 | + }).exceptionally(e -> { |
| 113 | + // if futures has fail op, abort this txn |
| 114 | + txn.abort(); |
| 115 | + return null; |
| 116 | + }); |
| 117 | + }).exceptionally(e -> { |
| 118 | + // new transaction fail, should redeliver this message or negativeAcknowledge |
| 119 | + // if you don't redeliver or negativeAcknowledge, the message will not receive again |
| 120 | + // ((ConsumerImpl<String>)consumer1).redeliverUnacknowledgedMessages(Collections.singleton(message.getMessageId())); |
| 121 | + // ((MultiTopicsConsumerImpl<String>)consumer1).redeliverUnacknowledgedMessages(Collections.singleton(message.getMessageId())); |
| 122 | + consumer1.negativeAcknowledge(message); |
| 123 | + return null; |
| 124 | + }); |
| 125 | + } catch (PulsarClientException e) { |
| 126 | + // client don't support transaction, please enable transaction enableTransaction(true) |
| 127 | + } |
| 128 | + }); |
| 129 | + } |
| 130 | + |
| 131 | + for (int i = 0; i < count; i++) { |
| 132 | + Message<String> message = consumer2.receive(); |
| 133 | + System.out.println("Receive transaction message: " + message.getValue()); |
| 134 | + } |
| 135 | + |
| 136 | + // release the io resource |
| 137 | + consumer2.close(); |
| 138 | + consumer1.close(); |
| 139 | + producer1.close(); |
| 140 | + producer2.close(); |
| 141 | + client.close(); |
| 142 | + } |
| 143 | +} |
0 commit comments