对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
点作为分隔符
当邮件路由到@MessageMapping
方法,它们与AntPathMatcher
.默认情况下,模式应使用 slash () 作为分隔符。
这是 Web 应用程序中的良好约定,类似于 HTTP URL。但是,如果
您更习惯于消息传递约定,可以切换到使用 DOT (/
.
) 作为分隔符。
以下示例显示了如何在 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 配置:
<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” 上的前缀,因为这些 完全依赖于外部 Message Broker。请参阅 STOMP 文档页面 用于查看 Destination Headers 支持的约定的代理。
另一方面,“简单代理”确实依赖于配置的PathMatcher
,因此,如果
切换分隔符,该更改也适用于 broker 和 broker 的匹配方式
destinations 从 message 到 subscriptions 中的模式。