點作為分隔符

當訊息被路由到 @MessageMapping 方法時,它們會與 AntPathMatcher 進行匹配。預設情況下,模式期望使用斜槓 (/) 作為分隔符。這在 Web 應用程式中是一個很好的約定,類似於 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。請參閱你使用的 broker 的 STOMP 文件頁面,瞭解它對目標 header 支援哪些約定。

另一方面,“simple broker”確實依賴於配置的 PathMatcher,因此,如果你切換分隔符,該更改也會應用於 broker 以及 broker 將訊息中的目標與訂閱模式匹配的方式。