简体   繁体   English

将 Websocket 与 Spring 引导和 Vuejs 一起使用的最佳方式

[英]Best way to use Websocket with Spring Boot and Vuejs

I try to use Websocket with spring boot backend (as an API) and Vuejs frontend.我尝试将 Websocket 与 spring 引导后端(作为 API)和 Vuejs 前端一起使用。

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.用户 A 向用户 B 发送消息。用户 B 实际已登录,我想通知用户 B 有新消息到达。

I see 3 ways to do it with websockets:我看到了 3 种使用 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 1 - 当用户 A 发送消息时,Axios 帖子被调用到 API 以保存消息,并且,如果 Axios 响应成功,我调用类似

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

2 - When User A send message, I only call something like 2 - 当用户 A 发送消息时,我只调用类似

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这是我的控制器的方法(用@MessageMapping(“/xxxx”)@SendTo(“/topic/yyyy”)注释)首先调用facade,service,dao,保存消息,然后将消息返回给订阅者

3 - I keep my actuals controllers, facade, services and DAO, and juste add when save is successfull something like: 3 - 我保留我的实际控制器、外观、服务和 DAO,并在保存成功时添加,例如:

@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").没有新的 controller 包含 @MessageMapping("/xxxx") @SendTo("/topic/yyyy")。 User B is just subscibed to "/ws/message-from"用户 B 刚刚订阅了“/ws/message-from”

Could you help me.你可以帮帮我吗。

In the 3 way there is a good method?在3方式中有什么好的方法吗?

Thanks you.谢谢。

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.第一种和第二种方法没有太大区别,因为您使用 npm 中的 axios 发送请求,而另一种您可以直接使用,而第三种方法您使用 controller,以及您想在单个地方发送的外观。您对框架的要求,作为要求。

They serve best at their level,till you come with specific requirement.他们在他们的水平上提供最好的服务,直到你有特定的要求。

The suggestion would be to use axios.建议是使用 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM