当前位置: 首页 > 工具软件 > stomp > 使用案例 >

Spring STOMP @SubscribeMapping 的使用

江瀚昂
2023-12-01

使用方法

标记在方法上,用于将客户端以 “/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

 类似资料: