当消息被路由到带有 @MessageMapping
注解的方法时,它们会与 AntPathMatcher
进行匹配。默认情况下,模式(patterns)期望使用斜线(/
)作为分隔符。这是Web应用程序中的一个良好惯例,并且与HTTP URL类似。然而,如果你更习惯于消息传递的惯例,你可以切换到使用点(.
)作为分隔符。
以下示例展示了如何在Java配置中这样做:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
*// ...*@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setPathMatcher(new AntPathMatcher("."));
registry.enableStompBrokerRelay("/queue", "/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
以下示例展示了用XML进行配置的方法,和java配置方式的效果一样。
<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
方法中使用点(.
)作为分隔符,如下例所示:
@Controller
@MessageMapping("red")
public class RedController {
@MessageMapping("blue.{green}")
public void handleGreen(@DestinationVariable String green) {
*// ...*
}
}
客户端现在可以向 /app/red.blue.green123
发送消息。
在前面的示例中,我们没有更改“broker relay”上的前缀,因为这些完全取决于外部消息代理。请参阅你使用的消息代理的STOMP文档页面,了解它支持哪些目的地头的约定。
另一方面,“简单代理”确实依赖于配置的 PathMatcher
,因此,如果你切换了分隔符,这个变更也适用于代理以及代理将消息中的destination与订阅中的模式进行匹配的方式。