对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

点作为分隔符

当消息被路由到 @MessageMapping 方法时,它们会与 AntPathMatcher 匹配。默认情况下,模式应使用斜杠 (/) 作为分隔符。 这在Web应用程序中是一个很好的惯例,类似于HTTP URL。然而,如果您更习惯于消息传递约定,可以切换为使用点 (.) 作为分隔符。spring-doc.cadn.net.cn

以下示例展示了如何在Java配置中实现这一点:spring-doc.cadn.net.cn

@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配置等价写法:spring-doc.cadn.net.cn

<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 方法中使用点(.)作为分隔符, 如下面的示例所示:spring-doc.cadn.net.cn

@Controller
@MessageMapping("red")
public class RedController {

	@MessageMapping("blue.{green}")
	public void handleGreen(@DestinationVariable String green) {
		// ...
	}
}

客户端现在可以向 /app/red.blue.green123 发送消息。spring-doc.cadn.net.cn

在前面的示例中,我们没有更改“broker relay”的前缀,因为这些前缀完全取决于外部消息代理。请参阅您使用的代理的 STOMP 文档页面,以查看目标头支持哪些约定。spring-doc.cadn.net.cn

另一方面,“简单代理”依赖于配置的 PathMatcher,因此,如果您更改了分隔符,该更改也会应用到代理,并且代理匹配消息到订阅中的模式的方式也会改变。spring-doc.cadn.net.cn