简体   繁体   English

RESTful API - 批量操作的分块响应

[英]RESTful API - chunked response for bulk operation

I work on a REST-like API that will support bulk operations on some resources. 我正在研究类似REST的API,它将支持某些资源上的批量操作。 As it may take some time to finish such a request, I would like to return statuses of the operations in a chunked response. 由于完成此类请求可能需要一些时间,因此我希望在分块响应中返回操作的状态。 The media type should be JSON. 媒体类型应为JSON。 How to do it with JAX-RS? 如何使用JAX-RS?

(I know that there is StreamingOutput, but it needs to manually serialize the data.) (我知道有StreamingOutput,但它需要手动序列化数据。)

Chunked Transfer encoding is usually used in cases where the content length is unknown when the sender starts transmitting the data. Chunked Transfer编码通常用于发件人开始传输数据时内容长度未知的情况。 The receiver can handle each chunk while the server is still producing new ones. 接收器可以处理每个块,而服务器仍在生成新的块。 This implies the the server is sending the whole time. 这意味着服务器正在发送整个时间。 I don't think that it makes too much sense to send I'm still working|I'm still working|I'm still working| 我不认为发送I'm still working|I'm still working|I'm still working|太有意义了I'm still working|I'm still working|I'm still working| in chunks and as far as I know chunked transfer-encoding is handled transparently by most application servers. 在块中,据我所知,大多数应用服务器透明地处理分块传输编码。 They switch automatically when the response is bigger then a certain size. 当响应大于特定大小时,它们会自动切换。

A common pattern for your use case looks like this: 用例的常见模式如下所示:

The client triggers a bulk operation: 客户端触发批量操作:

POST /batch-jobs HTTP/1.1

The server creates a resource which describes the status of the job and returns the URI in the Location header: 服务器创建描述作业状态的资源,并在Location头中返回URI:

HTTP/1.1 202 Accepted
Location: /batch-jobs/stats/4711

The client checks this resource and receives a 200: 客户端检查此资源并收到200:

GET /batch-jobs/stats/4711 HTTP/1.1

This example uses JSON but you could also return plain text or add caching headers which tell the client how long he should wait for the next poll. 此示例使用JSON,但您也可以返回纯文本或添加缓存标头,告诉客户端他应该等待下一轮询的时间。

HTTP/1.1 200 OK
Content-Type: application/json

{ "status" : "running", "nextAttempt" : "3000ms" }

If the job is done the server should answer with a 303 and the URI of the resource he has created: 如果作业完成,服务器应回答303和他创建的资源的URI:

HTTP/1.1 303 See other
Location: /batch-jobs/4711

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

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