我在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具有一个称为“成功”的布尔字段,以指示操作是否成功。

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

最佳答案

我设法找到一种仅根据条件发送更新的方法

@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;
}

08-05 03:26