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