如果pubsub主题不可用,则引发未找到异常 [英] throw not found exception if pubsub topic is not available
问题描述
我正在使用Spring Boot与pubsub主题进行交互.
I am using spring boot to interact with pubsub topic.
此连接的配置类如下:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gcp.pubsub.core.PubSubTemplate;
import org.springframework.cloud.gcp.pubsub.core.publisher.PubSubPublisherTemplate;
import org.springframework.cloud.gcp.pubsub.support.PublisherFactory;
import org.springframework.cloud.gcp.pubsub.support.converter.SimplePubSubMessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.SettableListenableFuture;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.pubsub.v1.PubsubMessage;
public abstract class PubSubPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(PubSubPublisher.class);
private final PubSubTemplate pubSubTemplate;
protected PubSubPublisher(PubSubTemplate pubSubTemplate) {
this.pubSubTemplate = pubSubTemplate;
}
protected abstract String topic(String topicName);
public ListenableFuture<String> publish(String topicName, String message) {
LOGGER.info("Publishing to topic [{}]. Message: [{}]", topicName, message);
return pubSubTemplate.publish(topicName, message);
}
}
我正在为我服务,就像这样:
And I am calling this at my service, like this:
publisher.publish(topic-name, payload);
此发布方法是异步方法,该方法始终传递未等待确认.我在发布后进行添加获取,等待它获得pubsub的响应.
This publish method is async one, which always pass on did not wait for acknowldgrment. I make add get after publish for wait until it get the response from pubsub.
但是我想知道如果我的主题不存在并且我尝试推送一些消息,它应该抛出一些错误,例如找不到资源,而只考虑使用默认的异步方法.
But I wanted to know if in case my topic is not already present and i try to push some message, it should throw some error like resource not found, considering using default async method only.
可能实现回调将有所帮助,但是我无法在我的代码中做到这一点.并且当前使用回调的重写发布方法只是抛出WARN not exception,我希望将其作为例外.这就是我想要实现回调的原因.
Might be implementing the callback would help but i am unable to do that in my code. And the current override publish method which use callback is just throwing the WARN not exception i wanted that to be exception. that is the reason i wanted to implement the callback.
推荐答案
您可以检查主题是否已存在
You can check if Topic already present
from google.cloud import pubsub_v1
project_id = "projectname"
topic_name = "unknowTopic"
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)
try:
response = publisher.get_topic(topic_path)
except Exception as e:
print(e)
这将错误返回为
404 Resource not found (resource=unknowTopic).
这篇关于如果pubsub主题不可用,则引发未找到异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!