编程语言
首页 > 编程语言> > java-Spring session Spring Web套接字.根据会话ID向特定客户端发送消息

java-Spring session Spring Web套接字.根据会话ID向特定客户端发送消息

作者:互联网

我已经从堆栈溢出中遵循了Quetion1Quetion2,以根据其sessionId将消息发送到特定的客户端,但是找不到成功.

下面是我的示例RestController类

@RestController
public class SpringSessionTestApi {

@Autowired
public SimpMessageSendingOperations messagingTemplate;

@MessageMapping("/messages")
public void greeting(HelloMessage message, SimpMessageHeaderAccessor headerAccessor) throws Exception {

    String sessionId  = (String) headerAccessor.getSessionAttributes().get("SPRING.SESSION.ID");
    messagingTemplate.convertAndSendToUser(sessionId,"/queue/test",message, createHeaders(sessionId));

   }

private MessageHeaders createHeaders(String sessionId) {
    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
    headerAccessor.setSessionId(sessionId);
    headerAccessor.setLeaveMutable(true);
    return headerAccessor.getMessageHeaders();
   }
}

会话ID:当客户端发送createSession请求时,会生成新的spring sessionId并将其存储在MongoDB中.之后,当客户端发送Web套接字连接请求时,会收到相同的sessionId,该会话ID如预期那样存储在mongoDb中.直到一切正常.

现在,我的工作是根据sessionId将响应发送回客户端.
为此,我有下面的Web套接字类:

@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig extends
    AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> {

@Override
protected void configureStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/messages");
}

public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/queue");
    registry.setApplicationDestinationPrefixes("/app");
   }
}

和我用来连接的示例客户端代码是:

function connect() {

stompClient = Stomp.client('ws://localhost:8016/messages');
stompClient.debug = null;

stompClient.connect({}, function (frame) {
    setConnected(true);
    console.log('Connected: ' + frame);
    stompClient.subscribe('/user/queue/test', function (greeting) {
        console.log("Hello "+greeting);
        console.log("Greeting body "+JSON.parse(greeting.body));

    });
});
}

请帮助,我在哪里做错了?
提前致谢!

解决方法:

如果您正在使用/ user通道,请尝试按照所述here传递用户.

@MessageMapping("/messages")
public void greeting(HelloMessage message, SimpMessageHeaderAccessor headerAccessor, Principal principal) 
    throws Exception {
    messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/test", message);
}

标签:spring-websocket,java,spring,spring-session,stomp
来源: https://codeday.me/bug/20191011/1890048.html