Search code examples
javaspring-bootrabbitmqspring-websocketmessagebroker

How to modify each broker message for each receiver inside a channel individually in Spring Boot?


I'm sending a message to a channel but have to modify it for each client.

Anyone with experience on how to do that?


Solution

  • There you go.

    Spring offers interceptors for incoming and outgoing channels. So simply add an interceptor and you're ready to catch every in- and outgoing message and do whatever you want to.

    First your config:

    ...
    
    @Autowired
    private InboundMessagesChannelInterceptor inboundMessagesChannelInterceptor;
    
    @Autowired
    private OutboundMessagesChannelInterceptor outboundMessagesChannelInterceptor;
    
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(inboundMessagesChannelInterceptor);
    }
    
    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.interceptors(outboundMessagesChannelInterceptor);
    }
    
    ...
    

    and your interceptor:

    @Component
    public class OutboundMessagesChannelInterceptor implements ChannelInterceptor {
    
        @Override
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            // modify your message as needed
            return message;
        }
    
    }
    

    Thats it.