[英]Spring-Websocket: Send Updates to Subscribers when condition is met
I have the following method on a Spring @Controller: 我在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;}
This will send updates to all the subscribers even if the operation was not successful (operationResult.success == false). 即使操作不成功,这也将向所有订阅者发送更新(operationResult.success == false)。
NB: OperationResult has a boolean field called 'success' to indicate whether the operation was successful or not. 注意: OperationResult具有一个称为“成功”的布尔字段,以指示操作是否成功。
Question: I want to find out how can I only send updates to subscribers if the operation was successful (without throwing an exception) and ensure that the client that sent the comment always gets the operationResult 问题:我想了解如何仅在操作成功(不引发异常)的情况下将更新发送给订阅者,并确保发送评论的客户端始终获得operationResult
I managed to find a way to only send updates based on a condition 我设法找到一种仅根据条件发送更新的方法
@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;
}
This however does not allow me to return the operationResult to the client. 但是,这不允许我将operationResult返回给客户端。
UPDATE: 更新:
To allow the client to get the operationResult I replaced the @MessageMapping
with @RequestMapping
. 为了允许客户端获取operationResult,我将
@MessageMapping
替换为@RequestMapping
。 So the client has to make a normal ajax call to submit a comment. 因此,客户端必须进行正常的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.