我依靠以下pub / sub doc创建了java pub / sub consumer。
public static void main(String... args) throws Exception {
TopicName topic = TopicName.create(pubSubProjectName, pubSubTopic);
SubscriptionName subscription = SubscriptionName.create(pubSubProjectName, "ssvp-sub");
SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create();
subscriptionAdminClient.createSubscription(subscription, topic, PushConfig.getDefaultInstance(), 0);
MessageReceiver receiver =
new MessageReceiver() {
@Override
public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
System.out.println("Got message: " + message.getData().toStringUtf8());
consumer.ack();
}
};
Subscriber subscriber = null;
try {
subscriber = Subscriber.defaultBuilder(subscription, receiver).build();
subscriber.addListener(
new Subscriber.Listener() {
@Override
public void failed(Subscriber.State from, Throwable failure) {
// Handle failure. This is called when the Subscriber encountered a fatal error and is shutting down.
System.err.println(failure);
}
},
MoreExecutors.directExecutor());
subscriber.startAsync().awaitRunning();
Thread.sleep(60000);
} finally {
if (subscriber != null) {
subscriber.stopAsync();
}
}
}
它运行良好,但每次运行都会通过抛出 StatusRuntimeException 异常来请求新的订阅者名称。
io.grpc.StatusRuntimeException: ALREADY_EXISTS: Resource already exists in the project (resource=ssvp-sub).
(请参阅我的代码段中 SubscriptionName.create(pubSubProjectName," ssvp-sub")行)
我发现在node.js客户端中我们可以传递" reuseExisting:true" 选项来重用现有订阅:
topic.subscribe('maybe-subscription-name', { reuseExisting: true }, function(err, subscription) {
// subscription was "get-or-create"-ed
});
如果我使用官方的java pubsub客户端,我应该通过什么选项?:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
<version>0.13.0-alpha</version>
</dependency>
答案 0 :(得分:4)
Java库没有允许用现有订阅调用createSubscription并且没有抛出异常的方法。您有两个选项,两个选项都涉及使用try / catch块。选择取决于您是否希望对订阅的存在持乐观态度。
悲观的电话:
try {
subscriptionAdminClient.createSubscription(subscription,
topic,
PushConfig.getDefaultInstance(),
0);
} catch (ApiException e) {
if (e.getStatusCode() != Status.Code.ALREADY_EXISTS) {
throw e;
}
}
// You know the subscription exists and can create a Subscriber.
乐观的电话:
try {
subscriptionAdminClient.getSubscripton(subscription);
} catch (ApiException e) {
if (e.getStatusCode() == Status.Code.NOT_FOUND) {
// Create the subscription
} else {
throw e;
}
}
// You know the subscription exists and can create a Subscriber.
通常情况下,通常会在启动订阅者之前创建订阅(通过Cloud Console或gcloud CLI),因此您甚至可能希望执行getSubscription()
调用并抛出无论如何都是例外。如果订阅被删除,您可能希望引起对这种情况的注意并明确地处理它,因为它有影响(比如不再存储消息以传递给订阅的事实)。
但是,如果你正在做一些像构建缓存服务器那样只需要在启动和运行时瞬间获得更新的东西,那么在启动时创建订阅是有意义的。