Spring session + Spring web socket。根据会话ID将消息发送到特定客户端

时间:2017-04-21 07:28:54

标签: java spring stomp spring-websocket spring-session

我已经从堆栈溢出跟踪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,它按预期存储在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));

    });
});
}

请帮忙,我在哪里做错了? 在此先感谢!

2 个答案:

答案 0 :(得分:0)

如果您正在使用/ user频道,请尝试按照说明here传递用户。

CREATE TABLE admin.FctPrfitAmt_rpt AS 
    SELECT rcn.* FROM 
    (
        SELECT t1.* 
        FROM admin.FctPrfitAmt t1 
        LEFT JOIN admin.FctPrfitAmt_incr t2
        ON t1.scenario_id = t2.scenario_id
        WHERE t2.scenario_id IS NULL
        UNION ALL
        SELECT * FROM admin.FctPrfitAmt_incr
    ) rcn
;

答案 1 :(得分:0)

我在git中找到了一个完整可用的Spring Stomp Chat项目,链接就在这里。你可以参考它。 https://gist.github.com/theotherian/9906304