使用点号作为分隔符

当消息被路由到@MessageMapping 方法时,它们与AntPathMatcher匹配。默认情况下,期望模式使用斜杠 (/) 作为分隔符。这是 Web 应用程序中一个良好的约定,类似于 HTTP URL。但是,如果您更习惯于消息传递约定,则可以使用点 (.) 作为分隔符。

以下示例演示了如何操作

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

	// ...

	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.setPathMatcher(new AntPathMatcher("."));
		registry.enableStompBrokerRelay("/queue", "/topic");
		registry.setApplicationDestinationPrefixes("/app");
	}
}

之后,控制器可以使用点 (.) 作为@MessageMapping 方法中的分隔符,如下例所示

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

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

客户端现在可以向/app/red.blue.green123发送消息。

在前面的示例中,我们没有更改“代理中继”上的前缀,因为这些完全取决于外部消息代理。请参阅您使用的代理的 STOMP 文档页面,以了解其支持的目标标头约定。

另一方面,“简单代理”确实依赖于配置的PathMatcher,因此,如果您切换分隔符,则该更改也适用于代理以及代理如何将消息中的目标与订阅中的模式匹配。