Search code examples
google-cloud-platformgoogle-cloud-pubsubmicronaut

Set a Pub Sub topic in Micronaut as per environment


I am following this guide to initialise a GCP Pub/Sub publisher.

The coding syntax is as follows:

@PubSubClient
public interface PubSubService {

    @Topic("topic-a")
    void send(final A a);

    @Topic("topic-b")
    void send(final B b);

}

I want to set this topic value based on the environment, as I will have a different topic for QA/DEV (say topic-a-qa and topic-b-qa). Is there any way for me to set this String value in the @Topic annotation via or based on environment properties?

I do not have an option of have a different Project under the GCP account, also creating a different class for QA overriding this one is not so graceful when maintaining environments.


Solution

  • You can use placeholders inside Micronaut's annotations.

    @PubSubClient
    public interface PubSubService {
    
        @Topic("${topic.a.name:topic-a}")
        void send(final A a);
    
        @Topic("${topic.b.name:topic-b}")
        void send(final B b);
    
    }
    

    The expression ${topic.a.name:topic-a} instructs Micronaut to search for the value in the configuration under the topic.a.name key, and fall back to the value topic-a if the configuration key is not found. Then you can configure different topic names using e.g. application-qa.yml configuration file:

    src/main/resources/application-qa.yml

    topic:
      a:
        name: topic-a-qa
      b:
        name: topic-b-qa
    

    Lastly, just make sure that when you run the application in the QA environment you set a proper active environment, e.g.

    $ java -Dmicronaut.environments=qa -jar myapp.jar