代码之家  ›  专栏  ›  技术社区  ›  Virat

spring boot web socket中的实时通知

  •  4
  • Virat  · 技术社区  · 7 年前

    在我的应用程序中,我需要向特定用户发送实时通知。 我的 WebSocketConfig 等级如下:,

        @Configuration
        @EnableWebSocketMessageBroker
        public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
            @Override
            public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
                stompEndpointRegistry.addEndpoint("/websocket-example")
                        .withSockJS();
            }
    
            @Override
            public void configureMessageBroker(MessageBrokerRegistry registry) {
                registry.enableSimpleBroker("/topic");
        }
    }
    

    大多数情况下,信息将由服务器端发送。因此,我没有设置应用程序目标。

    在客户端,我订阅目标“/主题/用户”,

    function connect() {
        var socket = new SockJS('/websocket-example');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/user', function (greeting) {
    //            showGreeting(JSON.parse(greeting.body).content);
    console.log("Received message through WS");
            });
        });
    }
    

    在我的 RestController 我有一个向所有连接的客户端广播消息的方法。

        @GetMapping("/test")
        public void test()
        {
            template.convertAndSend("/topic/user", "Hurray");
        }
    

    在这部分之前,一切正常。我收到消息并正在登录控制台。

    现在,如果我只想向特定用户发送通知,我必须使用 template.convertAndSendToUser(String user, String destination, String message) . 但我不明白我应该把什么传给 user 参数我将在何时何地获得 使用者 ?

    我问了几个与此相关的问题,但我不清楚这些概念。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Vadim Dissa    7 年前

    在向用户发送任何消息之前,您需要首先通过服务器对其进行身份验证。有不同的方法可以做到这一点。春季安全性是这里的一个关键短语

    https://docs.spring.io/spring-security/site/docs/current/guides/html5/helloworld-boot.html

    身份验证完成后,只需调用以下命令即可获取用户名:

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String currentPrincipalName = authentication.getName();
    

    https://www.baeldung.com/get-user-in-spring-security

        2
  •  0
  •   Devratna    7 年前

    username java.security.Principal interface . 每个StompHeaderAccessor或WebSocket会话对象都有一个此原则的实例,您可以从中获取用户名。它不是自动生成的。 It has to be generated manually by the server for every session.

    您可以检查 here 有关为每个会话生成唯一id的详细信息。

    然后像这样使用:

    @MessageMapping('/test')
    public void test(SimpMessageHeaderAccessor sha)
    {
      String userName = sha.session.principal.name;
      template.convertAndSend(userName, '/topic/user', "Hurray");
    }