• Spring STOMP @SubscribeMapping 的使用


    使用方法

    标记在方法上,用于将客户端以 “/app” 开头的订阅路由到对应的方法上。默认情况下,返回值会通过clientOutboundChannel直接返回(发送)给客户端,不经过broker,是一次性的。用户可以通过 @SendTo@SendToUser 去修改这一行为,也就是将返回值发送个broker,然后广播出去。

    方法参数

    Method argumentDescription
    MessageFor access to the complete message.
    MessageHeadersFor access to the headers within the Message.
    MessageHeaderAccessor, SimpMessageHeaderAccessor, and StompHeaderAccessorFor access to the headers through typed accessor methods.
    @PayloadFor access to the payload of the message, converted (for example, from JSON) by a configured MessageConverter.


    The presence of this annotation is not required since it is, by default, assumed if no other argument is matched.


    You can annotate payload arguments with @javax.validation.Valid or Spring’s @Validated, to have the payload arguments be automatically validated.

    @HeaderFor access to a specific header value — along with type conversion using an org.springframework.core.convert.converter.Converter, if necessary.
    @HeadersFor access to all headers in the message. This argument must be assignable to java.util.Map.
    @DestinationVariableFor access to template variables extracted from the message destination. Values are converted to the declared method argument type as necessary.
    java.security.PrincipalReflects the user logged in at the time of the WebSocket HTTP handshake.

    用途

    一般用于初始化数据。如登入聊天室后,初始化在线人员列表和历史消息等。不是真正的订阅。

    代码示例:

    服务端:

    registry.enableStompBrokerRelay("/topic");
    registry.setApplicationDestinationPrefixes("/app");
    
    @SubscribeMapping("/chatroom")
    public List<String> chatInit(){
        List<String> onlineList = new ArrayList<>();
        onlineList.add("Kleven");
        onlineList.add("Dean");
        return onlineList;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    客户端:

    stompClient.subscribe('/app/chatroom', (msg) => {
        // client logic
    });
    
    • 1
    • 2
    • 3

    结果:

    >>> SUBSCRIBE
    id:sub-1
    destination:/app/chatroom
    
    <<< MESSAGE
    destination:/app/chatroom
    content-type:application/json
    subscription:sub-1
    message-id:e1vkwn0p-0
    content-length:17
    
    ["Kleven","Dean"]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    官方文档

    https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#websocket-stomp-subscribe-mapping

  • 相关阅读:
    微信小程序 工具使用(HBuilderX)
    【零散技术】Odoo 服务台(helpdesk)Qweb设计模式
    02 控制器《ThinkPHP6 入门到电商实战》
    Java程序员薪资大比拼,网友:竟然达标了?
    docker 集群管理实战mesos+zookeeper+marathon(一)
    回归算法中特征线性相关会怎样
    unique_ptr的大小探讨
    基于 StarRocks 的风控实时特征探索和实践
    【Nginx】Nginx相关知识整理
    移动无线点餐客户端的研究与实现(Java+Android)
  • 原文地址:https://blog.csdn.net/u012359704/article/details/125628194