点作为分隔符
当消息被路由到 @MessageMapping
方法时,它们会与 AntPathMatcher
进行匹配。默认情况下,模式预计使用斜杠 (/
) 作为分隔符。这在 web 应用程序中是一个良好的约定,并且与 HTTP URL 类似。然而,如果您更习惯于消息传递约定,可以切换为使用点 (.
) 作为分隔符。
以下示例展示了如何做到这一点:
- 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”的前缀,因为这些完全依赖于外部消息代理。请参阅您使用的代理的 STOMP 文档页面,以了解它支持的目标头的约定。
另一方面,“简单代理”确实依赖于配置的 PathMatcher
,因此,如果您更改分隔符,该更改也会应用于代理,以及代理将消息中的目标与订阅中的模式进行匹配的方式。