Indrajeet Gour
Indrajeet Gour

Reputation: 4500

Spring boot: push message to specific topic for each request

I am using pub sub integration with spring boot, for which my configuration class look like this:

@Configuration
public class PubSubConfiguration {

    @Value("${spring.pubsub.topic.name}")
    private String topicName;

    @Bean
    @ServiceActivator(inputChannel = "MyOutputChannel")
    public PubSubMessageHandler messageSender(PubSubTemplate pubsubTemplate) {
        return new PubSubMessageHandler(pubsubTemplate, topicName);
    }

    @MessagingGateway(defaultRequestChannel = "MyOutputChannel")
    public interface PubsubOutboundGateway {
        void sendToPubsub(String attribute);
    }

}

So now, I was calling only sendToPubSub method which add payload into topic from my app, like this:

@Autowired
private PubSubConfiguration.PubsubOutboundGateway outboundGateway;

// used line in my code wherever is needed. 
outboundGateway.sendToPubsub(jsonInString);

The above code is just meant for one topic which i loaded from application property file.

But now I wanted to make my topic name is dynamically added into messageSender, how to do that.

Upvotes: 1

Views: 1190

Answers (2)

Sadashiv Gour
Sadashiv Gour

Reputation: 21

To override the default topic you can use the GcpPubSubHeaders.TOPIC header.

final Message<?> message = MessageBuilder
        .withPayload(msg.getPayload())
        .setHeader(GcpPubSubHeaders.TOPIC, "newTopic").build();

and modify your sendToPubsub(Message<byte[]> message) to use message as input.

Refer for more information

Upvotes: 2

Lauren
Lauren

Reputation: 999

Consider creating a BeanFactory to generate a PubSubMessageHandler Bean given a topic name. PubSubMessageHandler also has a setTopic() method, which may be of use.

Upvotes: 1

Related Questions