当消息被路由到 @MessageMapping方法时,它们会与 AntPathMatcher 匹配。默认情况下,模式被期望使用斜线(/)作为分隔符。这在网络应用中是一个很好的惯例,与 HTTP URLs 类似。然而,如果你更习惯于 信息传递的惯例,你可以切换到使用点(.)作为分隔符。
下面的例子显示了如何在 Java 配置中这样做:
@Configuration@EnableWebSocketMessageBrokerpublic class WebSocketConfig implements WebSocketMessageBrokerConfigurer {// ...@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {registry.setPathMatcher(new AntPathMatcher("."));registry.enableStompBrokerRelay("/queue", "/topic");registry.setApplicationDestinationPrefixes("/app");}}
下面是 XML 格式的配置
<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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/websockethttps://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方法中使用点(.)作为分隔符,如下图所示:
@Controller@MessageMapping("red")public class RedController {@MessageMapping("blue.{green}")public void handleGreen(@DestinationVariable String green) {// ...}}
客户端现在可以向 /app/red.blue.green123发送一个消息。
在前面的例子中,我们没有改变 「broker relay」的前缀,因为这些完全取决于外部的消息代理。请看你使用的消息代理的 STOMP 文档页面,看看它对目标 header 支持什么约定。
另一方面,简单代理 确实依赖于配置的 PathMatcher,所以,如果你切换分离器,这种改变也适用于代理和代理将消息中的目的地与订阅中的模式相匹配的方式。
