0

我在 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),这也会向所有订阅者发送更新。

注意: OperationResult 有一个名为“success”的布尔字段来指示操作是否成功。

问题: 我想了解如何仅在操作成功(不抛出异常)的情况下向订阅者发送更新,并确保发送评论的客户端始终获得operationResult

4

1 回答 1

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;
}
于 2015-11-10T20:37:32.243 回答