I have the following method on a 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).
NB: OperationResult has a boolean field called 'success' to indicate whether the operation was successful or not.
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
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.
UPDATE:
To allow the client to get the operationResult I replaced the @MessageMapping
with @RequestMapping
. So the client has to make a normal ajax call to submit a comment.
@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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.