Best way to use Websocket with Spring Boot and Vuejs

Viewed 1154

I try to use Websocket with spring boot backend (as an API) and Vuejs frontend.

I take a simple use case to expose my question. Some users are logged on my website, and there is a messaging feature. User A send a message to User B. User B is actually logged, and I want to notify User B that a new message is arrived.

I see 3 ways to do it with websockets :

1 - When User A send message, an Axios post is call to the API for saving message, and, if the Axios response is success, I call something like

this.stompClient.send("/app/foo", JSON.stringify(bar), {})

2 - When User A send message, I only call something like

this.stompClient.send("/app/foo", JSON.stringify(bar), {})

and it's my controller's method (annotated with @MessageMapping("/xxxx") @SendTo("/topic/yyyy")) that call facade, service, dao to first, save message, then return message to subscribers

3 - I keep my actuals controllers, facade, services and DAO, and juste add when save is successfull something like :

@Autowired SimpMessagingTemplate webSocket; 
...
@GetMapping("/send-message")
public ResponseEntity sendMessage(@AuthenticationPrincipal User user, ....) {
    service.saveMessage(....);
    webSocket.convertAndSend("/ws/message-from", message);

without a new controller contains @MessageMapping("/xxxx") @SendTo("/topic/yyyy"). User B is just subscibed to "/ws/message-from"

Could you help me.

In the 3 way there is a good method ?

Thanks you.

1 Answers

The one and two method has no much difference as you use axios from npm for sending request and the other one you can directly,while the third one you use controller,and facade dao at single place.it is about architecture and how you wanna send your requests for your framework,as a requirement.

They serve best at their level,till you come with specific requirement.

The suggestion would be to use axios. It has advantages:

supports older browsers (Fetch needs a polyfill)
has a way to abort a request
has a way to set a response timeout
has built-in CSRF protection
supports upload progress
performs automatic JSON data transformation
works in Node.js
Related