问题描述
我正在考虑使用websockets和http来构建REST API,我使用websockets告诉客户端新数据可用或直接将新数据提供给客户端.
I am thinking about buildning a REST API with both websockets and http where I use websockets to tell the client that new data is available or provide the new data to the client directly.
以下是有关其工作方式的一些不同想法:
ws = websocket
Here are some different ideas of how it could work:
ws = websocket
想法A:
- David使用
GET /users
获取所有用户 - Jacob使用
POST /users
添加用户 - ws消息会发送给所有客户端,并带有新用户存在的信息
- David通过ws接收一条消息并呼叫
GET /users
- David get all users with
GET /users
- Jacob add a user with
POST /users
- A ws message is sent to all clients with info that a new user exist
- David recive a message by ws and calls
GET /users
想法B:
- David使用
GET /users
获取所有用户 - 对
/users
进行更改后,David进行注册以获取ws更新. - Jacob使用
POST /users
添加用户 - ws将新用户发送给David
- David get all users with
GET /users
- David register to get ws updates when a change is done to
/users
- Jacob add a user with
POST /users
- The new user is sent to David by ws
想法C:
- David使用
GET /users
获取所有用户 - 对
/users
进行更改后,David进行注册以获取ws更新. - Jacob使用
POST /users
添加一个用户,并获得ID 4 - David通过ws接收新用户的ID 4
- David使用
GET /users/4
获得新用户
- David get all users with
GET /users
- David register to get ws updates when a change is done to
/users
- Jacob add a user with
POST /users
and it gets the id 4 - David receive the id 4 of the new user by ws
- David get the new user with
GET /users/4
想法D:
- David使用
GET /users
获取所有用户 - 在对
/users
进行更改后,David进行注册以获取ws更新. - Jacob使用
POST /users
添加用户 - David收到一条ws消息,提示已更改
/users
- David通过调用
GET /users?lastcall='time of step one'
只能获得增量
- David get all users with
GET /users
- David register to get ws updates when changes is done to
/users
. - Jacob add a user with
POST /users
- David receive a ws message that changes is done to
/users
- David get only the delta by calling
GET /users?lastcall='time of step one'
哪种选择是最好的,优缺点是什么?
是另一个更好的"Idea E"吗?
我们甚至需要使用REST还是对所有数据都足够?
Which alternative is the best and what are the pros and cons?
Is it another better 'Idea E'?
Do we even need to use REST or is ws enought for all data?
修改
为了解决数据不同步的问题,我们可以提供标题
"If-Unmodified-Since"
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/If-Unmodified-Since
或"E-Tag"
https: //developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/ETag
或两者都带有PUT请求.
Edit
To solve problems with data getting out of sync we could provide the header
"If-Unmodified-Since"
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Unmodified-Since
or "E-Tag"
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
or both with PUT requests.
推荐答案
对我来说,想法B是最好的,因为客户端专门订阅资源中的更改,并从那一刻开始获取增量更新.
Idea B is for me the best, because the client specifically subscribes for changes in a resource, and gets the incremental updates from that moment.
这篇关于如何结合websockets和http创建一个REST API,以保持数据最新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!