我在桌面应用程序中使用google cloud pubsub java library。我为特定主题创建订阅并从中接收数据。我想知道是否可以配置订阅的邮件保留期限。我在任何地方都找不到。谢谢。
为使问题更清楚,我粘贴了用于创建订阅的代码块:
String topicName = "some-topic";
String subscriptionName = "some-subscription";
ProjectTopicName topic = ProjectTopicName.of(PROJECT_ID, topicName);
ProjectSubscriptionName subscription = ProjectSubscriptionName.of(PROJECT_ID, subscriptionName);
SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create(); // I reuse this object so I create it in advance
try {
subscriptionAdminClient.createSubscription(subscription,
topic,
PushConfig.getDefaultInstance(),
0
);
} catch (ApiException e) {
if (e.getStatusCode().getCode() != StatusCode.Code.ALREADY_EXISTS) {
subscriptionAdminClient.close();
}
}
答案 0 :(得分:1)
您可以使用Java配置订阅的消息保留期限。创建598 * 3600 * 1000 = 2,152,800,000
对象时,可以在创建请求中提供message_retention_duration field
。要在Java中执行此操作,请使用setMessageRetentionDuration
method on Subscription.Builder
对象,如本例所示(使用long
依赖项):
Subscription
请注意,com.google.cloud:google-cloud-pubsub:1.86.0
采用Duration
作为参数,因此您可能需要使用Durations
helper class(例如package com.example;
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.Subscription;
import com.google.pubsub.v1.TopicName;
import com.google.protobuf.util.Durations;
import java.io.IOException;
public class PubSubCreateSubscription {
static Subscription createSubscriptionWithMessageRetentionDuration(
String topicName,
String subscriptionName,
long messageRetentionDurationInMillis
) throws IOException {
try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
Subscription request = Subscription.newBuilder()
.setName(subscriptionName)
.setTopic(topicName)
.setMessageRetentionDuration(Durations
.fromMillis(messageRetentionDurationInMillis))
.build();
return subscriptionAdminClient
.createSubscription(request);
}
}
public static void main(String[] args)
{
String topicName = "projects/[PROJECT]/topics/[TOPIC_NAME]";
String subscriptionName = "projects/[PROJECT]/subscriptions/[SUBSCRIPTION_NAME]";
try {
Subscription mySubscription = createSubscriptionWithMessageRetentionDuration(
topicName,
subscriptionName,
600000 // 600 000 ms = 10 minutes
);
// [...]
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法)将毫秒转换为protobuf {{ 1}}。还要注意from the REST resource documentation,此字段:
不能超过7天或少于10分钟。