Skip to content

Commit

Permalink
Transaction example (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
congbobo184 authored May 24, 2022
1 parent dc1ea8c commit 30a1820
Show file tree
Hide file tree
Showing 7 changed files with 394 additions and 0 deletions.
3 changes: 3 additions & 0 deletions cloud/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ This directory includes examples of how Pulsar CLI tools and Pulsar clients conn
- [Go client](https://github.com/streamnative/pulsar-examples/tree/master/cloud/go)
- [Python client](https://github.com/streamnative/pulsar-examples/tree/master/cloud/python)
- [Node.js client](https://github.com/streamnative/pulsar-examples/tree/master/cloud/node)

- Supported Pulsar transactions
- [Java client](https://github.com/streamnative/examples/tree/master/cloud/transaction/java)

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.

Expand Down
6 changes: 6 additions & 0 deletions cloud/transaction/README.md
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)
36 changes: 36 additions & 0 deletions cloud/transaction/java/README.md
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
```
56 changes: 56 additions & 0 deletions cloud/transaction/java/pom.xml
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>
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;
}
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();
}
}
Loading

0 comments on commit 30a1820

Please sign in to comment.