Reputation: 1258
we have a common use case for our applications where we have long lived Topics that could span across application deploys but may also not exist.
We are trying to find the best practice for the pattern in GCP pub/sub topics using the provided Java client where we can CreateIfNotExists, or GetAndCreateIfNotExists.
The current implementation we are using is to attempt to create a Topic and basically swallow the exception if it is AlreadyExistsException.
@Override
public void createTopicIfNotExists(TopicName topicName) {
try {
this.topicAdminClient.createTopic(topicName);
} catch (AlreadyExistsException e) {
// topic already exists
} catch (Exception e) {
throw e;
}
}
I don't think this is ideal because are basically using an exception as logic which is inherently bad practice. If we try to get a topic when it doesn't exist the client throws a DoesNot exist exception so we can't do it the other way.
I have seen things on github about the JS client being able to autoCreate on a Get command, does anyone know if that is available in the java client.
See here: https://stackoverflow.com/a/38878368/5385625 Is there an equivalent in the Java client.
Upvotes: 2
Views: 2135
Reputation: 356
The recommended approach is to catch the NotFoundEception
on getTopic
for knowing when a topic already exists. Is there a particular concern you have with processing the exception in this way?
Upvotes: 1
Reputation: 7277
Unfortunately this feature is not available in the java client library. You can file a feature request since this is a potential useful feature!
What I could suggest is prior to creating a topic you can perform getTopic() to check if a topic is existing or not, to prevent having exceptions.
Sample code from getTopic()
Java docs:
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
Topic response = topicAdminClient.getTopic(topic.toString());
}
Upvotes: 3