我正在尝试配置订阅映射,以在春季启动应用程序中通过websocket踩踏,但没有任何运气。我很确定我已经正确配置了stomp / websocket东西,因为我可以订阅由kafka消费者发布的主题,但是使用@SubscribeMapping根本不起作用。
这是我的控制人
@Controller
class TestController {
@SubscribeMapping("/topic/test")
fun testMapping(): String {
return "THIS IS A TEST"
}
}
这是我的配置
@Configuration
@EnableWebSocketMessageBroker
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
class WebSocketConfig : AbstractWebSocketMessageBrokerConfigurer() {
override fun configureMessageBroker(config: MessageBrokerRegistry) {
config.setApplicationDestinationPrefixes("/app", "/topic")
config.enableSimpleBroker("/queue", "/topic")
config.setUserDestinationPrefix("/user")
}
override fun registerStompEndpoints(registry:StompEndpointRegistry) {
registry.addEndpoint("/ws").setAllowedOrigins("*")
}
override fun configureClientInboundChannel(registration: ChannelRegistration?) {
registration?.setInterceptors(object: ChannelInterceptorAdapter() {
override fun preSend(message: Message<*>, channel: MessageChannel): Message<*> {
val accessor: StompHeaderAccessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor::class.java)
if (StompCommand.CONNECT.equals(accessor.command)) {
Optional.ofNullable(accessor.getNativeHeader("authorization")).ifPresent {
val token = it[0]
val keyReader = KeyReader()
val creds = Jwts.parser().setSigningKey(keyReader.key).parseClaimsJws(token).body
val groups = creds.get("groups", List::class.java)
val authorities = groups.map { SimpleGrantedAuthority(it as String) }
val authResult = UsernamePasswordAuthenticationToken(creds.subject, token, authorities)
SecurityContextHolder.getContext().authentication = authResult
accessor.user = authResult
}
}
return message
}
})
}
}
然后在UI代码中,我使用stompjs包装器使用angular来订阅它,如下所示:
this.stompService.subscribe('/topic/test')
.map(data => data.body)
.subscribe(data => console.log(data));
像这样订阅我所知道的正在发射数据的主题可以很好地工作,但是subscribemapping没有作用。我还尝试过将事件侦听器添加到我的websocket配置中,以测试UI实际上是向后端发送订阅事件,如下所示:
@EventListener
fun handleSubscribeEvent(event: SessionSubscribeEvent) {
println("Subscription event: $event")
}
@EventListener
fun handleConnectEvent(event: SessionConnectEvent) {
println("Connection event: $event")
}
@EventListener
fun handleDisconnectEvent(event: SessionDisconnectEvent) {
println("Disconnection event: $event")
}
添加这些事件侦听器,我可以看到我期望从UI中获得的所有事件都在kotlin层中通过,但是我的控制器方法从未被调用。有什么明显的我想念的吗?
答案 0 :(得分:2)
尝试以下操作:
@Controller
class TestController {
@SubscribeMapping("/test")
fun testMapping(): String {
return "THIS IS A TEST"
}
}