我正在尝试将一个目标变量应用到我的控制器中处理来自WebSocket的传入消息的方法。这是我想要实现的:
@Controller
public class DocumentWebsocketController {
@MessageMapping("/lock-document")
@SendTo("/notify-open-documents/{id}")
public Response response(@DestinationVariable("id") Long id, Message message) {
return new Response(message.getDocumentId());
}
}
问题在于,目标变量仅应用于
@SendTo
注释。 这将导致在尝试访问此端点时出现以下堆栈跟踪:12:36:43.044 [clientInboundChannel-7] ERROR org.springframework.web.socket.messaging.WebSocketAnnotationMethodMessageHandler - Unhandled exception
org.springframework.messaging.MessageHandlingException: Missing path template variable 'id' for method parameter type [class java.lang.Long]
at org.springframework.messaging.handler.annotation.support.DestinationVariableMethodArgumentResolver.handleMissingValue(DestinationVariableMethodArgumentResolver.java:70) ~[spring-messaging-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.messaging.handler.annotation.support.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:96) ~[spring-messaging-4.2.4.RELEASE.jar:4.2.4.RELEASE]
(...)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_144]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_144]
我的问题是:我想要实现的这种功能是否可能?
@DestinationVariable
。@DestinationVariable
只能用于@MessageMapping
/@SubscribeMapping
中的占位符,而不能用于@SendTo
中。错误提示说你想要获取一个叫做“id”的东西,但你没有在目标中定义它。为了拥有一个动态返回目标,其中包含与原始目标不同的占位符,你必须使用MessagingTemplate。 - Sergi Almar