簡體   English   中英

Spring-Websocket:在滿足條件時將更新發送給訂戶

[英]Spring-Websocket: Send Updates to Subscribers when condition is met

我在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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM