点作为分隔符

当消息被路由到@MessageMapping方法时,它们会与AntPathMatcher进行匹配。默认情况下,模式应该使用斜杠(/)作为分隔符。这是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配置等效项:

<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文档页面。

另一方面,“simple broker”依赖于配置的PathMatcher,因此,如果切换分隔符,该更改也适用于代理和代理将消息与订阅中的模式匹配的方式。