How to add custom headers to STOMP CREATED message in Spring Boot application?

有些话、适合烂在心里 提交于 2019-12-06 21:31:26
TheReALDeAL

Maybe it's too late, but better late than never ...

Server messages (e.g. CONNECTED) are immutable, means that they cannot be modified.

What I would do is register a client outbound interceptor and trap the connected message by overriding the preSend(...) method and build a new message with my custom headers.

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) 
{
    LOGGER.info("Outbound channel pre send ...");
    final StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(message);
    final StompCommand command = headerAccessor.getCommand();
    if (!isNull(command)) {
        switch (command) {
            case CONNECTED:
                final StompHeaderAccessor accessor = StompHeaderAccessor.create(headerAccessor.getCommand());
                accessor.setSessionId(headerAccessor.getSessionId());
                @SuppressWarnings("unchecked")
                final MultiValueMap<String, String> nativeHeaders = (MultiValueMap<String, String>) headerAccessor.getHeader(StompHeaderAccessor.NATIVE_HEADERS);
                accessor.addNativeHeaders(nativeHeaders);

                // add custom headers
                accessor.addNativeHeader("CUSTOM01", "CUSTOM01");

                final Message<?> newMessage = MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());
                return newMessage;
            default:
                break;
            }
        }
        return message;
    }

@UPDATE:::

The interface needed is called ChannelInterceptor and to register your own implementation you need to add @Configuration annotated class

@Configuration
public class CustomMessageBrokerConfig extends WebSocketMessageBrokerConfigurationSupport
implements WebSocketMessageBrokerConfigurer{}

and override a method configureClientOutboundChannel as below

@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
    log.info("Configure client outbound channel started ...");
    registration.interceptors(new CustomOutboundChannelInterceptor());
    log.info("Configure client outbound channel completed ...");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!