我在Spring @Controller上有以下方法:
@MessageMapping("/comment/{id}")
@SendTo("/topic/conversation/{id}")
public OperationResult<Comment> comment(Comment comment) throws Exception {
//call @Service to add comment
OperationResult<Comment> operationResult = commentService.comment(comment);
return operationResult;}
即使操作不成功,这也会向所有订阅者发送更新(operationResult.success == false)。
NB: OperationResult有一个名为“success”的布尔字段,用于指示操作是否成功。
问题: 我想知道如果操作成功,我怎么才能向订阅者发送更新(不抛出异常)并确保发送评论的客户端始终获得 operationResult
答案 0 :(得分:1)
我设法找到了一种只根据条件发送更新的方法
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@MessageMapping("/comment/{id}" )
public OperationResult<Comment> comment(Comment comment) throws Exception {
OperationResult<Comment> operationResult = new OperationResult<>();
conversationService.comment(operationResult, comment);
if (operationResult.isSuccess()) {
simpMessagingTemplate.convertAndSend("/topic/conversation/"+operationResult.getReturnedObject().getConversation().getId(), operationResult);
}
return operationResult;
}
然而,这不允许我将 operationResult 返回给客户端。
<强>更新强>
为了让客户端获得 operationResult ,我将@MessageMapping
替换为@RequestMapping
。因此,客户必须进行正常的ajax调用才能提交评论。
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@RequestMapping("/comment" )
public OperationResult<Comment> comment(@RequestBody Comment comment) throws Exception {
OperationResult<Comment> operationResult = new OperationResult<>();
conversationService.comment(operationResult, comment);
if (operationResult.isSuccess()) {
simpMessagingTemplate.convertAndSend("/topic/conversation/"+operationResult.getReturnedObject().getConversation().getId(), operationResult);
}
return operationResult;
}