點作為分隔符號

當訊息路由到 @MessageMapping 方法時,會使用 AntPathMatcher 進行匹配。預設情況下,模式預期使用斜線 (/) 作為分隔符號。這在網路應用程式中是一個良好的慣例,並且類似於 HTTP URL。但是,如果您更習慣訊息傳遞慣例,則可以切換為使用點 (.) 作為分隔符號。

以下範例示範如何執行此操作

  • Java

  • Kotlin

  • Xml

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

	// ...

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

	// ...

	override fun configureMessageBroker(registry: MessageBrokerRegistry) {
		registry.setPathMatcher(AntPathMatcher("."))
		registry.enableStompBrokerRelay("/queue", "/topic")
		registry.setApplicationDestinationPrefixes("/app")
	}
}
<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 方法中使用點 (.) 作為分隔符號,如下列範例所示

  • Java

  • Kotlin

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

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

	@MessageMapping("blue.{green}")
	fun handleGreen(@DestinationVariable green: String) {
		// ...
	}
}

用戶端現在可以傳送訊息到 /app/red.blue.green123

在前面的範例中,我們沒有變更「broker relay」上的前綴,因為這些前綴完全取決於外部訊息代理程式。請參閱您使用的 Broker 的 STOMP 文件頁面,以了解它支援的目的地標頭慣例。

另一方面,「simple broker」確實依賴已組態的 PathMatcher,因此,如果您切換分隔符號,則此變更也適用於 Broker 以及 Broker 將訊息中的目的地與訂閱中的模式進行匹配的方式。