如何使用Spring Boot Stomp在ChannelInterceptor中获取端点路径?

时间:2019-07-08 02:49:21

标签: spring-boot stomp

我是脚踏新手,使用Spring Boot 2.1.2.RELEASE。我有多个端点,并配置了ChannelInterceptor以获得一些信息。

@Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        registry.addEndpoint("/endpoint1")
                .addInterceptors(new IpHandshakeInterceptor())
                .setAllowedOrigins(origin)
                .withSockJS();

        registry.addEndpoint("/endpoint2")
                .addInterceptors(new IpHandshakeInterceptor())
                .setAllowedOrigins(origin)
                .withSockJS();
        // other andpoint
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(myChannelInterceptor());
    }

所有端点都使用myChannelInterceptor(实际上,我希望端点使用其自己的ChannelInterceptor),我希望按端点路径在ChannelInterceptor中进行操作。

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
  if (endpoint.equals("endpoint1")) {
  } else if (endpoint.equals("endpoint2")) {
  }
}

如何在endpoint中获取ChannelInterceptor信息?

1 个答案:

答案 0 :(得分:0)

您可以使用:

  1. 在IpHandshakeInterceptor类中,将值写入属性映射:

     @Override
     public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
         if (serverHttpRequest instanceof ServletServerHttpRequest) {
             ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
             HttpSession session = servletRequest.getServletRequest().getSession();
             //add value to session attributes
             map.put("endpoint", servletRequest.getURI().getPath());
         }
         // ... your logic ...
         return true;
     }
    
  2. 在您的myChannelInterceptor中,从会话属性中读取值:

     @Override
     public Message<?> preSend(final Message<?> message, final MessageChannel channel) throws AuthenticationException {
         final StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
         String endpoint=accessor.getSessionAttributes().get("endpoint").toString();
         // ... your logic ...
         return message;
     }