Skip to content

Commit 30a1820

Browse files
authored
Transaction example (#82)
1 parent dc1ea8c commit 30a1820

File tree

7 files changed

+394
-0
lines changed

7 files changed

+394
-0
lines changed

cloud/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ This directory includes examples of how Pulsar CLI tools and Pulsar clients conn
1818
- [Go client](https://github.com/streamnative/pulsar-examples/tree/master/cloud/go)
1919
- [Python client](https://github.com/streamnative/pulsar-examples/tree/master/cloud/python)
2020
- [Node.js client](https://github.com/streamnative/pulsar-examples/tree/master/cloud/node)
21+
22+
- Supported Pulsar transactions
23+
- [Java client](https://github.com/streamnative/examples/tree/master/cloud/transaction/java)
2124

2225
To use these tools or clients to connect to StreamNative Cloud, you need get the Pulsar service URLs of the StreamNative Cloud and OAuth2 or Token authentication parameters that are used to connect to the service URLs.
2326

cloud/transaction/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Overview
2+
3+
This directory includes examples of how to use transactions in cluster on a cluster with transaction enabled.
4+
5+
- Supported transaction clients
6+
- [Java client](https://github.com/streamnative/examples/tree/master/cloud/transaction/java)

cloud/transaction/java/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Overview
2+
3+
This document describes how to use transactions in cluster on a cluster with transaction enabled.
4+
5+
# Prerequisites
6+
7+
- Java 1.8 or higher version
8+
- Java Client: 2.8.0+
9+
- Maven
10+
11+
> **NOTE**
12+
>
13+
> This example uses Pulsar client 2.8.0. If you want to use another version of Pulsar client, you can change the `pulsar.version` property in `pom.xml` file.
14+
15+
# Example
16+
17+
1. Get the service URLs. For details, see [Get Pulsar service URLs](https://github.com/streamnative/pulsar-examples/tree/master/cloud#get-pulsar-service-urls).
18+
19+
2. Get the Oauth2 authentication parameters. For details, see [Get Oauth2 authentication parameters](https://github.com/streamnative/pulsar-examples/tree/master/cloud#get-oauth2-authentication-parameters).
20+
21+
3. Run the Java transaction example.
22+
23+
```shell script
24+
# Compile the Java code
25+
mvn clean package
26+
27+
# Run the example
28+
mvn exec:java -Dexec.mainClass="io.streamnative.examples.transaction.TransactionAsyncExample" \
29+
-Dexec.args="--serviceUrl pulsar+ssl://streamnative.cloud:6651 --audience urn:sn:pulsar:pulsar-instance-ns:pulsar-instance-name --issuerUrl https://streamnative.cloud --privateKey file:///path/to/private/key/file.txt"
30+
```
31+
**Output**:
32+
33+
```text
34+
Receive transaction message: Hello Pulsar! count : 1
35+
Receive transaction message: Hello Pulsar! count : 2
36+
```

cloud/transaction/java/pom.xml

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
16+
-->
17+
<project xmlns="http://maven.apache.org/POM/4.0.0"
18+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
19+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
20+
<modelVersion>4.0.0</modelVersion>
21+
22+
<groupId>org.example</groupId>
23+
<artifactId>transaction</artifactId>
24+
<version>1.0-SNAPSHOT</version>
25+
26+
<properties>
27+
<pulsar.version>2.10.0</pulsar.version>
28+
</properties>
29+
30+
<dependencies>
31+
<dependency>
32+
<groupId>org.apache.pulsar</groupId>
33+
<artifactId>pulsar-client</artifactId>
34+
<version>${pulsar.version}</version>
35+
</dependency>
36+
37+
<dependency>
38+
<groupId>com.beust</groupId>
39+
<artifactId>jcommander</artifactId>
40+
<version>1.29</version>
41+
</dependency>
42+
</dependencies>
43+
44+
<build>
45+
<plugins>
46+
<plugin>
47+
<groupId>org.apache.maven.plugins</groupId>
48+
<artifactId>maven-compiler-plugin</artifactId>
49+
<configuration>
50+
<source>8</source>
51+
<target>8</target>
52+
</configuration>
53+
</plugin>
54+
</plugins>
55+
</build>
56+
</project>
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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.Parameter;
21+
22+
import java.util.ArrayList;
23+
import java.util.List;
24+
25+
public class JCommanderPulsar {
26+
@Parameter(names = {"--issuerUrl"}, description = "issuerUrl is a named external system that provides identity and API access by issuing OAuth access tokens")
27+
String issuerUrl = "";
28+
29+
@Parameter(names = {"--privateKey"}, description = "the credentials URL")
30+
String credentialsUrl = "";
31+
32+
@Parameter(names = {"--serviceUrl"}, description = "serviceURL is the address of the accessed broker")
33+
String serviceUrl = "";
34+
35+
@Parameter(names = {"--audience"}, description = "audience is the address of the accessed service")
36+
String audience = "";
37+
38+
@Parameter(names = "--help", help = true)
39+
boolean help;
40+
}
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
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

Comments
 (0)