简体   繁体   English

从服务器端通知客户端的最佳实践?

[英]Best practice to notify client from serverside?

In my current situation, the frontend client is making an api call to a backend endpoint (java) at a 15 second interval to see if a resource exists.在我目前的情况下,前端客户端每隔 15 秒对后端端点 (java) 进行 api 调用,以查看资源是否存在。 The resource will be created through some business logic.资源将通过一些业务逻辑创建。 Once the resource exists, client will get the data from api and process it.一旦资源存在,客户端将从 api 获取数据并进行处理。

However, it seems that it is a costly performance and not scalable to call an api every 15 seconds.但是,每 15 秒调用一次 api 似乎是一种昂贵的性能并且不可扩展。 I was wondering the best practice for this - the client waiting for a resource to exist to execute some logic.我想知道这方面的最佳实践 - 客户端等待资源存在以执行某些逻辑。

Is there a way / best practice to send/push data from the server to the client rather than the other way around as well as being unidirectional (server -> client)..有没有一种方法/最佳实践将数据从服务器发送/推送到客户端,而不是相反以及单向(服务器->客户端)..

Thank you in advance.先感谢您。

In order to solve this properly you will need to implement WebSocket.为了正确解决这个问题,您需要实现 WebSocket。 The Request from the client will be a GET and the server will approve it with 200 status code to confirm.来自客户端的请求将是一个 GET,服务器将使用 200 状态码确认它。 Then,when the server will done process your request, it will broadcast the data via the websocket directly to your web application.然后,当服务器完成处理您的请求时,它将通过 websocket 将数据直接广播到您的 web 应用程序。

Is there a way / best practice to send/push data from the server to the client rather than the other way around as well as being unidirectional (server -> client)..有没有一种方法/最佳实践将数据从服务器发送/推送到客户端,而不是相反以及单向(服务器->客户端)..

What you've just described here is known as the observer pattern .您刚刚在此处描述的内容称为观察者模式 The whole idea of it is to have a list of observers attached to observables and push notifications each time the state of observable changes.它的整个想法是每次 state 的可观察变化时都有一个附加到可观察对象的观察者列表和推送通知。

You could implement this pattern in your Java back-end by exposing a subscription endpoint in which you'd specify what you want to observe, along with what URI to call back in case there's a state change, or some other mechanism for pushing server notifications.您可以在 Java 后端中实现此模式,方法是公开订阅端点,您可以在其中指定要观察的内容,以及在发生 state 更改或其他一些推送服务器通知的机制时回调的 URI . However, you might have to solve another problem which is having your "client" act as a server, permanently or temporarily, for these notifications, if you want to avoid periodic API queries.但是,如果您想避免定期的 API 查询,您可能必须解决另一个问题,即让您的“客户端”永久或临时充当这些通知的服务器。

Obviously, you want to have an 'unsubscribe' endpoint to free resources.显然,您希望有一个“取消订阅”端点来释放资源。 You might have to consider what to do if the client unexpectedly loses connection or is not engaging for some other reason (some time-to-live for subscription sounds like a good idea here).您可能必须考虑如果客户端意外断开连接或由于其他原因没有参与(订阅的生存时间在这里听起来是个好主意),该怎么办。

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

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