直接用户消息不适用于 Spring Websocket

Direct user message doesn't work with Spring Websocket

我正在尝试向用户发送直接消息。应用程序尚未完成身份验证,因此有创建 websocket 会话用户的临时解决方案,如您在添加的代码中所见。

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        registry.addEndpoint("/ws")
                .setHandshakeHandler(new CustomHandshakeHandler())
                .withSockJS();
    }

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

    // only for dev purpose
    public static class CustomHandshakeHandler extends DefaultHandshakeHandler {

        @Override
        protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
            String username = "user-123";
            return new StompPrincipal(username);
        }

        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        public static class StompPrincipal implements Principal {
            private String name;
        }
    }
}

这是我的 RabbitMQ 侦听器,它使用消息处理事件并通过 websockets 向测试用户 user-123 发送直接消息:

@RabbitListener(queues = "${event.queue.message-created}")
public void handleMessageCreatedEvent(MessageCreatedEvent event) {
    String devUser = "user-123";
    log.info("MSG received {}.", event); 
    simpMessagingTemplate.convertAndSendToUser(devUser, "/exchange/amq.direct/chat.message", event);
}

消息由 rabbit 侦听器处理并使用简单消息传递模板发送,但未在 javascript 中到达前端客户端。

以下是我尝试处理这些消息的方式:

$(function () {
    var stompClient;
    var wrappedSocket = {

        init: function (url) {
            stompClient = Stomp.over(new SockJS(url));
        },
        connect: function (successCallback, errorCallback) {

            stompClient.connect({}, function (frame) {
                successCallback(frame)
            }, function (error) {
                errorCallback(error)
            });
        },
        subscribe: function (destination, callback) {
            stompClient.subscribe(destination, function (message) {
                callback(message)
            });
        },
        send: function (destination, headers, object) {
            stompClient.send(destination, headers, object);
        }
    };


    wrappedSocket.init('/ws');

    wrappedSocket.connect(
        function (frame) {
            console.info('connected', frame)
        }, function (err) {
            console.error('not connected', err)
        }
    );

    wrappedSocket.subscribe("/user/exchange/amq.direct/chat.message", function(message) {
        console.log('NEW PRIVATE MESSAGE', message)
    });

    console.log("ready!");
});

我可以在浏览器控制台中看到客户端已成功连接并开始订阅给定频道,但没有收到任何消息。

你能告诉我如何解决吗?谢谢。

订阅应在连接建立后初始化,因此请尝试在成功回调中调用 wrappedSocket.subscribe()