Spring WebSockets - 如何仅将@DestinationVariable应用于@SendTo注释?

时间:2018-04-06 10:53:00

标签: spring spring-mvc websocket spring-websocket spring-4

我试图将目标变量应用于我的控制器中处理来自WebSocket的传入消息的方法。这就是我想要实现的目标:

// register add to cart action
function woocommerce_add_cart_button () {
    add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_add_to_cart', 10 );
}
add_action( 'after_setup_theme', 'woocommece_add_cart_button' );

问题是,目标变量仅应用于@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

我的问题是:就像我想要实现的那样?

2 个答案:

答案 0 :(得分:1)

这应该是可能的。我指的是以下答案:Path variables in Spring WebSockets @SendTo mapping

  

更新:在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);
}

答案 1 :(得分:1)

您收到的错误告诉您目的地中没有名为id的占位符(在@MessageMapping中定义)。 @DestinationVariable尝试从传入目标获取变量,它似乎没有像您尝试那样绑定到传出目标。但是,您可以在@MessageMapping内的@SendTo内使用目的地中的相同占位符(但这不是您的情况)。

如果您想拥有动态目的地,请使用MessagingTemplate之类的:

@MessageMapping("/lock-document")
public void response(Message message) {
    simpMessagingTemplate.convertAndSend("/notify-open-documents/" + message.getDocumentId(), new Response(message.getDocumentId());
}
相关问题