我非常喜欢@SubscribeMapping方法,用STOMP-over-Websocket实现类似RPC的语义。
不幸的是,它的“魔力”要求带注释的方法返回一个值。但是,如果没有现成的返回值怎么办?我想避免在等待它的方法中阻塞。相反,我想传递一个回调,它将在它准备好时发布一个值。我以为我可以在回调中使用消息传递模板的convertAndSendToUser()来做到这一点。事实证明@SubscribeMapping处理是非常特殊的,并且对于SimpMessageSendingOperations的实例是不可能的。
我能够通过在SubscriptionMethodReturnValueHandler上调用handleReturnValue()来实现我的目标,但是如果不是hackish(例如向handleReturnValue()提供MethodParameter的虚拟实例),则整体机制非常繁琐:
public class MessageController {
private final SubscriptionMethodReturnValueHandler subscriptionMethodReturnValueHandler;
@Autowired
public MessageController(SimpAnnotationMethodMessageHandler annotationMethodMessageHandler) {
SubscriptionMethodReturnValueHandler subscriptionMethodReturnValueHandler = null;
for (HandlerMethodReturnValueHandler returnValueHandler : annotationMethodMessageHandler.getReturnValueHandlers()) {
if (returnValueHandler instanceof SubscriptionMethodReturnValueHandler) {
subscriptionMethodReturnValueHandler = (SubscriptionMethodReturnValueHandler) returnValueHandler;
break;
}
}
this.subscriptionMethodReturnValueHandler = subscriptionMethodReturnValueHandler;
}
@SubscribeMapping("/greeting/{name}")
public void greet(@DestinationVariable String name, Message<?> message) throws Exception {
subscriptionMethodReturnValueHandler.handleReturnValue("Hello " + name, new MethodParameter(Object.class.getMethods()[0], -1), message);
}
}
所以我的问题很简单:有更好的方法吗?