Asynchronous API calls
1. Polling for results
// Result: The actual response from the API.
// Status: QUEUED, IN_PROGRESS, COMPLETED, or FAILED.
// TaskId: The task ID.
// UsageMap: The usage map.
{
"RequestId": "01A11A0C-40B0-1181-B848-7FF74C3DB014",
"Message": "Success",
"Data": {
"Status": "COMPLETED",
"TaskId": "TID_3d32692c-ae96-438b-b1cd-3d5046e8280e",
"Result": "Actual API output structure",
"BizId": "Pass-through business ID from the caller"
},
"Code": "success",
"Success": true
}2. RocketMQ subscription
1. Procedure
Obtain the production endpoint, consumer group, consumer credentials, and the decryption key for your UID from your service provider.
Configure your subscription with a
uid-apiTypetag and start the consumer.After receiving a message, parse the encrypted envelope and decrypt it using your user key with AES-256-GCM.
Ensure idempotent processing based on
Data.TaskId. Determine the task result based onData.Status.Acknowledge consumption only after business data persistence is successful. If an exception occurs, return a consumption failure.
Before you begin:
The consumer credentials for ApsaraMQ for RocketMQ and the message decryption key are separate credentials. Do not use them interchangeably.
Your client needs only its user key. Do not obtain the server-side master key or replicate the server-side key derivation tool.
Result notifications may be duplicated or missed due to delivery failures. Implement the result query API as a fallback. Do not assume a task has failed just because a notification was not received.
2. Subscription rules
Message metadata:
Parameter | Description |
Topic | The result topic from your service provider. |
Key | The |
Tag |
|
Body | A UTF-8 encoded JSON string of the encrypted envelope. |
For example, if the UID is 1234567890 and the API code is api-a, the tag is:
1234567890-api-a
To subscribe to multiple APIs for the same UID, use a filter expression like this:
1234567890-api-a||1234567890-api-b
A message has only one tag. In a filter expression, || acts as a logical OR. Tag matching is case-sensitive and requires an exact match. 1234567890-* does not represent a prefix match for UIDs. Do not use * to subscribe to an entire shared topic. All instances in the same consumer group must have identical subscriptions. Use different consumer groups for different subscription needs. message filtering
3. Message format and encryption protocol
3.1 Message body: the encrypted envelope
{
"Version": 2,
"Algorithm": "AES-256-GCM",
"Iv": "<Base64-encoded 12-byte IV>",
"Ciphertext": "<Base64-encoded ciphertext and authentication tag>"
}
3.2 Decrypted business result
{
"RequestId": null,
"Code": "success",
"Success": true,
"Message": "Success",
"Data": {
"Status": "COMPLETED",
"Result": "{\"text\":\"Translated text\"}",
"TaskId": "task-001",
"BizId": "Pass-through business ID from the caller",
"UsageMap": {}
}
}
Example of a failed result:
{
"Status": "FAILED",
"TaskId": "task-001",
"BizId": "Pass-through business ID from the caller",
"Result": "{\"errorCode\":\"<actual error code>\",\"errorMessage\":\"<failure reason>\"}",
"UsageMap": null
}
4. Integration
4.1 POM dependency
<dependencies>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client-java</artifactId>
<version>5.0.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.30</version>
</dependency>
</dependencies>
4.2 Java decryption utility (standalone)
Obtain the keySecret from your service provider.
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;
public final class AsyncTaskResultDecryptor {
private AsyncTaskResultDecryptor() {}
public static JSONObject decryptMessage(byte[] body, String keySecret)
throws GeneralSecurityException {
if (body == null || body.length == 0
|| keySecret == null || keySecret.isBlank()) {
throw new IllegalArgumentException("body and keySecret are required");
}
JSONObject envelope = JSON.parseObject(new String(body, StandardCharsets.UTF_8));
if (envelope == null || !Integer.valueOf(2).equals(envelope.get("Version"))
|| !"AES-256-GCM".equals(envelope.get("Algorithm"))) {
throw new IllegalArgumentException("Unsupported encryption protocol");
}
String ivBase64 = envelope.getString("Iv");
String ciphertextBase64 = envelope.getString("Ciphertext");
if (ivBase64 == null || ivBase64.isBlank()
|| ciphertextBase64 == null || ciphertextBase64.isBlank()) {
throw new IllegalArgumentException("Iv and Ciphertext are required");
}
byte[] key = Base64.getDecoder().decode(keySecret);
byte[] iv = Base64.getDecoder().decode(ivBase64);
byte[] ciphertext = Base64.getDecoder().decode(ciphertextBase64);
if (key.length != 32 || iv.length != 12 || ciphertext.length < 16) {
throw new IllegalArgumentException("Invalid key, IV or ciphertext length");
}
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
new GCMParameterSpec(128, iv));
byte[] plaintext = cipher.doFinal(ciphertext);
JSONObject result = JSON.parseObject(new String(plaintext, StandardCharsets.UTF_8));
if (result == null) {
throw new IllegalArgumentException("Result JSON is required");
}
return result;
}
}
4.3 Java consumer integration example
4.3.1 Configuration
This section explains the configuration items. Do not commit actual passwords or keys to your code repository. This example reads settings from environment variables. In a production environment, use a key management system or controlled configuration injection instead.
ASYNC_MQ_ENDPOINTS=rmq-cn-x684z19du01.cn-beijing.rmq.aliyuncs.com:8080
ASYNC_MQ_NAMESPACE=rmq-cn-x684z19du01
ASYNC_MQ_TOPIC=ASYNC_TASK_RESULT_TOPIC
ASYNC_MQ_GROUP=CID_ASYNC_TASK_RESULT_{UID}
ASYNC_MQ_USERNAME=<consumer account from your service provider>
ASYNC_MQ_PASSWORD=<consumer password from your service provider>
ASYNC_MQ_UID=1234567890
ASYNC_MQ_API_TYPES=api-a,api-b
ASYNC_RESULT_KEY_SECRET=<user key for this UID, from your service provider>
4.3.2 Consume, decrypt, and acknowledge
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.StaticSessionCredentialsProvider;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.FilterExpressionType;
import org.apache.rocketmq.client.apis.consumer.PushConsumer;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public final class AsyncTaskResultConsumer {
private static final Logger LOG = Logger.getLogger(AsyncTaskResultConsumer.class.getName());
@FunctionalInterface
public interface ResultHandler {
// Return normally only after persisting business data or confirming the operation as idempotent. Throw an exception on failure.
void handle(String taskId, String tag, JSONObject result) throws Exception;
}
public static PushConsumer start(ResultHandler handler) throws Exception {
Objects.requireNonNull(handler, "handler");
String uid = required("ASYNC_MQ_UID");
Set<String> tags = Arrays.stream(required("ASYNC_MQ_API_TYPES").split(",", -1))
.map(String::trim)
.map(apiType -> {
if (apiType.isEmpty() || apiType.contains("|") || apiType.contains("*")) {
throw new IllegalArgumentException("Invalid apiType");
}
return uid + "-" + apiType;
})
.collect(Collectors.toSet());
String keySecret = required("ASYNC_RESULT_KEY_SECRET");
if (Base64.getDecoder().decode(keySecret).length != 32) {
throw new IllegalArgumentException("Expected a 32-byte AES key");
}
var config = ClientConfiguration.newBuilder()
.setEndpoints(required("ASYNC_MQ_ENDPOINTS"))
.setCredentialProvider(new StaticSessionCredentialsProvider(
required("ASYNC_MQ_USERNAME"), required("ASYNC_MQ_PASSWORD")));
String namespace = System.getenv("ASYNC_MQ_NAMESPACE");
if (namespace != null && !namespace.isBlank()) {
config.setNamespace(namespace);
}
FilterExpression filter = new FilterExpression(
tags.stream().sorted().collect(Collectors.joining("||")),
FilterExpressionType.TAG);
return ClientServiceProvider.loadService().newPushConsumerBuilder()
.setClientConfiguration(config.build())
.setConsumerGroup(required("ASYNC_MQ_GROUP"))
.setSubscriptionExpressions(Map.of(required("ASYNC_MQ_TOPIC"), filter))
.setConsumptionThreadCount(8)
.setMessageListener(message -> {
try {
String tag = message.getTag().orElseThrow();
if (!tags.contains(tag)) {
throw new IllegalArgumentException("Unexpected message tag");
}
ByteBuffer buffer = message.getBody().duplicate();
byte[] body = new byte[buffer.remaining()];
buffer.get(body); // Do not assume the ByteBuffer has an accessible array.
JSONObject result = AsyncTaskResultDecryptor.decryptMessage(body, keySecret);
JSONObject data = result.getJSONObject("Data");
if (data == null || data.getString("TaskId") == null
|| data.getString("TaskId").isBlank()) {
throw new IllegalArgumentException("Data.TaskId is required");
}
String status = data.getString("Status");
if (status == null || !Set.of("COMPLETED", "FAILED", "CANCELLED").contains(status)) {
throw new IllegalArgumentException("Unexpected task status");
}
handler.handle(data.getString("TaskId"), tag, result);
return ConsumeResult.SUCCESS;
} catch (Exception e) {
// Do not log credentials, message body, plaintext, or business content from exceptions.
LOG.warning("Async result consumption failed, messageId="
+ message.getMessageId() + ", errorType=" + e.getClass().getSimpleName());
return ConsumeResult.FAILURE;
}
})
.build();
}
private static String required(String name) {
String value = System.getenv(name);
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Missing environment variable: " + name);
}
return value;
}
}