对于最新稳定版本,请使用 Spring Framework 7.0.6spring-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 文档页面,以了解其对目标(destination)头支持哪些约定。spring-doc.cadn.net.cn

另一方面,“简单代理”(simple broker)确实依赖于所配置的PathMatcher,因此,如果你更改了分隔符,该更改也会应用于代理,以及代理将消息中的目标与订阅中的模式进行匹配的方式。spring-doc.cadn.net.cn