-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
dc1ea8c
commit 30a1820
Showing
7 changed files
with
394 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
# Overview | ||
|
||
This directory includes examples of how to use transactions in cluster on a cluster with transaction enabled. | ||
|
||
- Supported transaction clients | ||
- [Java client](https://github.com/streamnative/examples/tree/master/cloud/transaction/java) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# Overview | ||
|
||
This document describes how to use transactions in cluster on a cluster with transaction enabled. | ||
|
||
# Prerequisites | ||
|
||
- Java 1.8 or higher version | ||
- Java Client: 2.8.0+ | ||
- Maven | ||
|
||
> **NOTE** | ||
> | ||
> 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. | ||
# Example | ||
|
||
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). | ||
|
||
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). | ||
|
||
3. Run the Java transaction example. | ||
|
||
```shell script | ||
# Compile the Java code | ||
mvn clean package | ||
|
||
# Run the example | ||
mvn exec:java -Dexec.mainClass="io.streamnative.examples.transaction.TransactionAsyncExample" \ | ||
-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" | ||
``` | ||
**Output**: | ||
|
||
```text | ||
Receive transaction message: Hello Pulsar! count : 1 | ||
Receive transaction message: Hello Pulsar! count : 2 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<!-- | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
--> | ||
<project xmlns="http://maven.apache.org/POM/4.0.0" | ||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||
<modelVersion>4.0.0</modelVersion> | ||
|
||
<groupId>org.example</groupId> | ||
<artifactId>transaction</artifactId> | ||
<version>1.0-SNAPSHOT</version> | ||
|
||
<properties> | ||
<pulsar.version>2.10.0</pulsar.version> | ||
</properties> | ||
|
||
<dependencies> | ||
<dependency> | ||
<groupId>org.apache.pulsar</groupId> | ||
<artifactId>pulsar-client</artifactId> | ||
<version>${pulsar.version}</version> | ||
</dependency> | ||
|
||
<dependency> | ||
<groupId>com.beust</groupId> | ||
<artifactId>jcommander</artifactId> | ||
<version>1.29</version> | ||
</dependency> | ||
</dependencies> | ||
|
||
<build> | ||
<plugins> | ||
<plugin> | ||
<groupId>org.apache.maven.plugins</groupId> | ||
<artifactId>maven-compiler-plugin</artifactId> | ||
<configuration> | ||
<source>8</source> | ||
<target>8</target> | ||
</configuration> | ||
</plugin> | ||
</plugins> | ||
</build> | ||
</project> |
40 changes: 40 additions & 0 deletions
40
...transaction/java/src/main/java/io/streamnative/examples/transaction/JCommanderPulsar.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// Licensed to the Apache Software Foundation (ASF) under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. The ASF licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
package io.streamnative.examples.transaction; | ||
|
||
import com.beust.jcommander.Parameter; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
|
||
public class JCommanderPulsar { | ||
@Parameter(names = {"--issuerUrl"}, description = "issuerUrl is a named external system that provides identity and API access by issuing OAuth access tokens") | ||
String issuerUrl = ""; | ||
|
||
@Parameter(names = {"--privateKey"}, description = "the credentials URL") | ||
String credentialsUrl = ""; | ||
|
||
@Parameter(names = {"--serviceUrl"}, description = "serviceURL is the address of the accessed broker") | ||
String serviceUrl = ""; | ||
|
||
@Parameter(names = {"--audience"}, description = "audience is the address of the accessed service") | ||
String audience = ""; | ||
|
||
@Parameter(names = "--help", help = true) | ||
boolean help; | ||
} |
143 changes: 143 additions & 0 deletions
143
...tion/java/src/main/java/io/streamnative/examples/transaction/TransactionAsyncExample.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
// Licensed to the Apache Software Foundation (ASF) under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. The ASF licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
package io.streamnative.examples.transaction; | ||
|
||
import com.beust.jcommander.JCommander; | ||
|
||
import java.net.URL; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.concurrent.CompletableFuture; | ||
import java.util.concurrent.TimeUnit; | ||
import org.apache.pulsar.client.api.Consumer; | ||
import org.apache.pulsar.client.api.Message; | ||
import org.apache.pulsar.client.api.Producer; | ||
import org.apache.pulsar.client.api.ProducerBuilder; | ||
import org.apache.pulsar.client.api.PulsarClient; | ||
import org.apache.pulsar.client.api.PulsarClientException; | ||
import org.apache.pulsar.client.api.Schema; | ||
import org.apache.pulsar.client.api.transaction.TransactionCoordinatorClientException; | ||
import org.apache.pulsar.client.impl.auth.oauth2.AuthenticationFactoryOAuth2; | ||
import org.apache.pulsar.common.util.FutureUtil; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
public class TransactionAsyncExample { | ||
private static final Logger log = LoggerFactory.getLogger(TransactionAsyncExample.class); | ||
public static void main(String[] args) throws Exception { | ||
JCommanderPulsar jct = new JCommanderPulsar(); | ||
JCommander jCommander = new JCommander(jct, args); | ||
if (jct.help) { | ||
jCommander.usage(); | ||
return; | ||
} | ||
|
||
String topic1 = "persistent://public/default/topic-1"; | ||
String topic2 = "persistent://public/default/topic-2"; | ||
|
||
PulsarClient client = PulsarClient.builder() | ||
.enableTransaction(true) | ||
.serviceUrl(jct.serviceUrl) | ||
.authentication( | ||
AuthenticationFactoryOAuth2.clientCredentials(new URL(jct.issuerUrl), new URL(jct.credentialsUrl), jct.audience)) | ||
.build(); | ||
|
||
ProducerBuilder<String> producerBuilder = client.newProducer(Schema.STRING).enableBatching(false); | ||
Producer<String> producer1 = producerBuilder.topic(topic1).sendTimeout(0, TimeUnit.SECONDS).create(); | ||
Producer<String> producer2 = producerBuilder.topic(topic2).sendTimeout(0, TimeUnit.SECONDS).create(); | ||
|
||
Consumer<String> consumer1 = client.newConsumer(Schema.STRING).subscriptionName("test").topic(topic1).subscribe(); | ||
Consumer<String> consumer2 = client.newConsumer(Schema.STRING).subscriptionName("test").topic(topic2).subscribe(); | ||
|
||
int count = 2; | ||
// First prepare two messages that can be consumed | ||
for (int i = 0; i < count; i++) { | ||
producer1.send("Hello Pulsar! count : " + i); | ||
} | ||
|
||
for (int i = 0; i < count; i++) { | ||
// Consume two messages and send two messages to topic-2 with the same transaction | ||
// Receive the message first, and then start the transaction after receiving the message. | ||
// If the transaction is started first and no message is received for | ||
// a long time, it will cause the transaction to time out. | ||
final int number = i; | ||
consumer1.receiveAsync().thenAccept(message -> { | ||
// receive message success then new transaction | ||
try { | ||
client.newTransaction().withTransactionTimeout(10, TimeUnit.SECONDS).build().thenAccept(txn -> { | ||
// new transaction success, then you can do you own op | ||
List<CompletableFuture<?>> futures = new ArrayList<>(); | ||
// add send message with txn future to futures | ||
futures.add(producer2.newMessage(txn).value("Hello Pulsar! count : " + number).sendAsync()); | ||
// add ack message with txn future to futures | ||
futures.add(consumer1.acknowledgeAsync(message.getMessageId(), txn).exceptionally(e -> { | ||
if (!(e.getCause() instanceof PulsarClientException.TransactionConflictException)) { | ||
// if not TransactionConflictException, | ||
// we should redeliver or negativeAcknowledge this message | ||
// if you don't redeliver or negativeAcknowledge, the message will not receive again | ||
// ((ConsumerImpl<String>)consumer1).redeliverUnacknowledgedMessages(Collections.singleton(message.getMessageId())); | ||
// ((MultiTopicsConsumerImpl<String>)consumer1).redeliverUnacknowledgedMessages(Collections.singleton(message.getMessageId())); | ||
consumer1.negativeAcknowledge(message); | ||
} | ||
return null; | ||
})); | ||
|
||
FutureUtil.waitForAll(futures).thenRun(() -> { | ||
// futures are all success, then can commit this transaction | ||
txn.commit().thenRun(() -> { | ||
log.info("txn : {} commit success!", txn); | ||
}).exceptionally(e -> { | ||
log.error("txn : {} commit fail!", txn); | ||
// if not TransactionNotFoundException, you can commit again or abort. also you can wait txn timeout | ||
if (!(e.getCause() instanceof TransactionCoordinatorClientException.TransactionNotFoundException)) { | ||
txn.commit(); | ||
} | ||
return null; | ||
}); | ||
}).exceptionally(e -> { | ||
// if futures has fail op, abort this txn | ||
txn.abort(); | ||
return null; | ||
}); | ||
}).exceptionally(e -> { | ||
// new transaction fail, should redeliver this message or negativeAcknowledge | ||
// if you don't redeliver or negativeAcknowledge, the message will not receive again | ||
// ((ConsumerImpl<String>)consumer1).redeliverUnacknowledgedMessages(Collections.singleton(message.getMessageId())); | ||
// ((MultiTopicsConsumerImpl<String>)consumer1).redeliverUnacknowledgedMessages(Collections.singleton(message.getMessageId())); | ||
consumer1.negativeAcknowledge(message); | ||
return null; | ||
}); | ||
} catch (PulsarClientException e) { | ||
// client don't support transaction, please enable transaction enableTransaction(true) | ||
} | ||
}); | ||
} | ||
|
||
for (int i = 0; i < count; i++) { | ||
Message<String> message = consumer2.receive(); | ||
System.out.println("Receive transaction message: " + message.getValue()); | ||
} | ||
|
||
// release the io resource | ||
consumer2.close(); | ||
consumer1.close(); | ||
producer1.close(); | ||
producer2.close(); | ||
client.close(); | ||
} | ||
} |
Oops, something went wrong.