How to get Azure Service Bus message id when sending a message to a topic using Spring Integration

678 Views Asked by At

After I send a message to a topic on Azure Service Bus using Spring Integration I would like to get the message id Azure generates. I can do this using JMS. Is there a way to do this using Spring Integration? The code I'm working with:

@Service
public class ServiceBusDemo {
    private static final String OUTPUT_CHANNEL = "topic.output";
    private static final String TOPIC_NAME = "my_topic";

    @Autowired
    TopicOutboundGateway messagingGateway;

    public String send(String message) {
        // How can I get the Azure message id after sending here?
        this.messagingGateway.send(message);
        return message;
    }

    @Bean
    @ServiceActivator(inputChannel = OUTPUT_CHANNEL)
    public MessageHandler topicMessageSender(ServiceBusTopicOperation topicOperation) {
        DefaultMessageHandler handler = new DefaultMessageHandler(TOPIC_NAME, topicOperation);
        handler.setSendCallback(new ListenableFutureCallback<>() {
            @Override
            public void onSuccess(Void result) {
                System.out.println("Message was sent successfully to service bus.");
            }

            @Override
            public void onFailure(Throwable ex) {
                System.out.println("There was an error sending the message to service bus.");
            }
        });

        return handler;
    }

    @MessagingGateway(defaultRequestChannel = OUTPUT_CHANNEL)
    public interface TopicOutboundGateway {
        void send(String text);
    }
}
1

There are 1 best solutions below

0
On

You could use ChannelInterceptor to get message headers:

public class CustomChannelInterceptor implements ChannelInterceptor {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        //key of the message-id header is not stable, you should add logic here to check which header key should be used here.
        //ref: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/azure-spring-cloud-starter-servicebus#support-for-service-bus-message-headers-and-properties
        String messageId = message.getHeaders().get("message-id-header-key").toString();

        return ChannelInterceptor.super.preSend(message, channel);
    }

}

Then in the configuration, set this interceptor to your channel

    @Bean(name = OUTPUT_CHANNEL)
    public BroadcastCapableChannel pubSubChannel() {
        PublishSubscribeChannel channel = new PublishSubscribeChannel();
        channel.setInterceptors(Arrays.asList(new CustomChannelInterceptor()));
        return channel;
    }