点作为分隔符
当邮件路由到@MessageMapping
方法,它们与AntPathMatcher
.默认情况下,模式应使用 slash () 作为分隔符。
这是 Web 应用程序中的良好约定,类似于 HTTP URL。但是,如果
您更习惯于消息传递约定,可以切换到使用 DOT (/
.
) 作为分隔符。
以下示例显示了如何执行此作:
-
Java
-
Kotlin
-
Xml
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
// ...
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setPathMatcher(new AntPathMatcher("."));
registry.enableStompBrokerRelay("/queue", "/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfiguration : WebSocketMessageBrokerConfigurer {
// ...
override fun configureMessageBroker(registry: MessageBrokerRegistry) {
registry.setPathMatcher(AntPathMatcher("."))
registry.enableStompBrokerRelay("/queue", "/topic")
registry.setApplicationDestinationPrefixes("/app")
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/websocket
https://www.springframework.org/schema/websocket/spring-websocket.xsd">
<websocket:message-broker application-destination-prefix="/app" path-matcher="pathMatcher">
<websocket:stomp-endpoint path="/stomp"/>
<websocket:stomp-broker-relay prefix="/topic,/queue" />
</websocket:message-broker>
<bean id="pathMatcher" class="org.springframework.util.AntPathMatcher">
<constructor-arg index="0" value="."/>
</bean>
</beans>
之后,控制器可以使用点 (.
) 作为@MessageMapping
方法
如下例所示:
-
Java
-
Kotlin
@Controller
@MessageMapping("red")
public class RedController {
@MessageMapping("blue.{green}")
public void handleGreen(@DestinationVariable String green) {
// ...
}
}
@Controller
@MessageMapping("red")
class RedController {
@MessageMapping("blue.{green}")
fun handleGreen(@DestinationVariable green: String) {
// ...
}
}
客户端现在可以将消息发送到/app/red.blue.green123
.
在前面的示例中,我们没有更改 “broker relay” 上的前缀,因为这些 完全依赖于外部 Message Broker。请参阅 STOMP 文档页面 用于查看 Destination Headers 支持的约定的代理。
另一方面,“简单代理”确实依赖于配置的PathMatcher
,因此,如果
切换分隔符,该更改也适用于 broker 和 broker 的匹配方式
destinations 从 message 到 subscriptions 中的模式。