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;
}

客户端:

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

结果:

>>> 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"]

官方文档

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

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

i余数

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值