接口的幂等性

Idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. The concept of idempotence arises in a number of places in abstract algebra (in particular, in the theory of projectors and closure operators) and functional programming (in which it is connected to the property of referential transparency).
https://en.wikipedia.org/wiki/Idempotence

以上是 幂 等性的定义,大概意思是:在数学和计算机服务中,对于 某种操作执行多次,结果 相同。

接口为什么需要幂等性?

在计算机中,由于网络抖动,临时故障,服务调用失败避免不了,尤其是分布式系统中,接口调用失败更为常见,接口的幂等设计尤其更为重要。

Rest 中方法中的幂等性

  • GET: 获取资源,不对资源更新,属于幂等。
  • DELETE: 删除资源,由于在URI上指定了要删除资源,一次和多次的结果肯定相同,属于幂等。
  • POST 和PUT的幂等?

POST
The POST method requests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI. The data POSTed might be, for example, an annotation for existing resources; a message for a bulletin board, newsgroup, mailing list, or comment thread; a block of data that is the result of submitting a web form to a data-handling process; or an item to add to a database.
PUT
The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified; if the URI does not point to an existing resource, then the server can create the resource with that URI.

从HTTP 对POST和PUT的定义看出,POST是创建资源,PUT既可以创建也可以更新资源。
那Rest 中的POST和PUT应该这样使用:

  • POST URI: POST每次都创建新资源,应该不是幂等的。
POST URI:
✔http://www.xxx.com/orders
✖http://www.xxx.com/orders/1
  • PUT: PUT方法如果资源存在,就更新,如果不存在就创建 指定的资源,所以PUT是幂等的。
PUT URI:
http://www.xxx.com/orders/1
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,486评论 0 10
  • 去年11月,自己报名的心理咨询师要在武汉考,所以规划了这次之行,湖北其实早在读大学时,我和他借了两辆自行车...
    兔子拈花阅读 182评论 0 0
  • 我是你千百年前放生的白狐 千年前之恩 千年后来报 你看衣袂飘飘衣袂飘飘 夜深人静可有人看见我在跳舞 海誓山盟都化做...
    6b2740ac93e8阅读 257评论 0 0
  • 毕业季,我家也有小学生了,一个小学,一个幼儿园,这下白天至少家里安静了。
    高扬老师阅读 228评论 0 0
  • 最近纠结于朋友的关系。我记忆中完美的人,不过因为接触较少。那些活生生,有血有肉的,吵过架,撒过泼的,才是我一直...
    岢岚xd阅读 261评论 0 1