我正在尝试将目标变量应用于控制器中处理来自 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]
我的问题是:像我想要实现的东西有可能吗?
您得到的错误告诉您目标中没有名为id
的占位符(在您的@MessageMapping
中定义(。 @DestinationVariable
尝试从传入目标获取变量,它不会像您尝试的那样绑定到传出目标。但是,您可以在@SendTo
内使用目标@MessageMapping
中的相同占位符(但事实并非如此(。
如果要拥有动态目标,请使用如下MessagingTemplate
:
@MessageMapping("/lock-document")
public void response(Message message) {
simpMessagingTemplate.convertAndSend("/notify-open-documents/" + message.getDocumentId(), new Response(message.getDocumentId());
}
这应该是可能的。我指的是以下答案:Spring WebSockets 中的路径变量@SendTo映射
更新:在Spring 4.2中,支持目标变量占位符,现在可以执行以下操作:
@MessageMapping("/fleet/{fleetId}/driver/{driverId}")
@SendTo("/topic/fleet/{fleetId}")
public Simple simple(@DestinationVariable String fleetId, @DestinationVariable String driverId) {
return new Simple(fleetId, driverId);
}