RESTful API - 批量操作的分块响应 [英] RESTful API - chunked response for bulk operation

查看:207
本文介绍了RESTful API - 批量操作的分块响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发类似REST的API,支持某些资源的批量操作。由于完成此类请求可能需要一些时间,因此我希望在分块响应中返回操作的状态。媒体类型应为JSON。如何使用JAX-RS?

I work on a REST-like API that will support bulk operations on some resources. 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. How to do it with JAX-RS?

(我知道有StreamingOutput,但它需要手动序列化数据。)

(I know that there is StreamingOutput, but it needs to manually serialize the data.)

推荐答案

Chunked Transfer编码通常用于发件人开始传输数据时内容长度未知的情况。接收器可以处理每个块,而服务器仍在生成新的块。
这意味着服务器正在发送整个时间。我认为发送我没有太大意义我仍然在工作|我还在工作|我仍在工作| 一块块,并且就此而言我知道大多数应用服务器透明地处理分块传输编码。当响应大于特定大小时,它们会自动切换。

Chunked Transfer encoding is usually used in cases where the content length is unknown when the sender starts transmitting the data. 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| 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:

客户端触发批量操作:

POST /batch-jobs HTTP/1.1

服务器创建一个描述作业状态的资源,并在Location头中返回URI:

The server creates a resource which describes the status of the job and returns the URI in the Location header:

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

客户端检查此资源并收到200:

The client checks this resource and receives a 200:

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

此示例使用JSON但您也可以返回普通文本或添加缓存标题,告诉客户端他应该等待下一轮调查的时间。

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.

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

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

如果是作业已完成,服务器应回答303和他创建的资源的URI:

If the job is done the server should answer with a 303 and the URI of the resource he has created:

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

这篇关于RESTful API - 批量操作的分块响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆