如何在 Spring Boot 应用程序中向 STOMP CREATED 消息添加自定义标头?

Gli*_*lav 6 spring stomp websocket spring-boot spring-websocket

我正在尝试将自定义标头添加到客户端在第一次连接时收到的 STOMP 'CREATED' 消息中。这是使用 STOMP JavaScript 连接到 WebSocket 的函数:

function connect() {
    socket = new SockJS('/chat');
    stompClient = Stomp.over(socket);
    stompClient.connect('', '', function(frame) {
      whoami = frame.headers['user-name'];
      console.log(frame);
      stompClient.subscribe('/user/queue/messages', function(message) {
          console.log("MESSAGE RECEIVED:");
          console.log(message);

        showMessage(JSON.parse(message.body));
      });
      stompClient.subscribe('/topic/active', function(activeMembers) {
        showActive(activeMembers);
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

此函数将以下内容打印到浏览器的控制台:

body: ""
command: "CONNECTED"
headers: Object
    heart-beat: "0,0"
    user-name: "someuser"
    version: "1.1"
Run Code Online (Sandbox Code Playgroud)

我想添加自定义标题,因此输出必须如下所示:

body: ""
command: "CONNECTED"
headers: Object
    heart-beat: "0,0"
    user-name: "someuser"
    version: "1.1"
    custom-header: "foo"
Run Code Online (Sandbox Code Playgroud)

我的 Spring Boot 应用程序中有以下 WebSocket 配置。

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

  @Override
  public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/queue", "/topic");
    config.setApplicationDestinationPrefixes("/app");
  }

  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/chat", "/activeUsers")
            .withSockJS()
            .setInterceptors(customHttpSessionHandshakeInterceptor());
  }

  ...

  @Bean
  public CustomHttpSessionHandshakeInterceptor 
        customHttpSessionHandshakeInterceptor() {
        return new CustomHttpSessionHandshakeInterceptor();

  }

}
Run Code Online (Sandbox Code Playgroud)

我试图注册“HandshakeInterceptor”来设置自定义标头,但它没有用。这是“CustomHttpSessionHandshakeInterceptor”:

CustomHttpSessionHandshakeInterceptor.java

public class CustomHttpSessionHandshakeInterceptor implements 

HandshakeInterceptor {

     @Override
        public boolean beforeHandshake(ServerHttpRequest request,
        ServerHttpResponse response,
        WebSocketHandler wsHandler,
        Map<String, Object> attributes) throws Exception {
            if (request instanceof ServletServerHttpRequest) {


                 ServletServerHttpRequest servletRequest =
                    (ServletServerHttpRequest) request;
                 attributes.put("custom-header", "foo");
            }
            return true;
        }

        public void afterHandshake(ServerHttpRequest request,
            ServerHttpResponse response,
            WebSocketHandler wsHandler,
            Exception ex) { }
}
Run Code Online (Sandbox Code Playgroud)

我在https://dzone.com/articles/spring-boot-based-websocket 找到了这个代码片段
有人可以解释一下为什么这种方法不起作用吗?是否有另一种方法可以在 Spring Boot 应用程序的服务器端将自定义标头设置为 STOMP 'CREATED' 消息?
谢谢!

小智 0

你有这样尝试过吗?MessageHeaderAccessor 也有一个 setHeader 方法。 https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-authentication-token-based

  • 是的,我尝试使用“MessageHeaderAccessor”,它非常适合使用 STOMP“MESSAGE”命令的消息(对于由 Spring 的“@MessageMapping”注释的方法处理的普通消息,在我的情况下由“SimpMessagingTemplate”发送)。问题是如何使用 STOMP 'CONNECTED' 命令添加消息的自定义标头(该命令是在建立 WebSocket 连接后由服务器发送的)? (2认同)