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
以上是 冪 等性的定義逼侦,大概意思是:在數(shù)學和計算機服務中垃喊,對于 某種操作執(zhí)行多次室埋,結果 相同悔耘。
接口為什么需要冪等性诫惭?
在計算機中驮宴,由于網(wǎng)絡抖動沛简,臨時故障,服務調用失敗避免不了贪壳,尤其是分布式系統(tǒng)中迂曲,接口調用失敗更為常見,接口的冪等設計尤其更為重要寥袭。
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是創(chuàng)建資源凡伊,PUT既可以創(chuàng)建也可以更新資源。
那Rest 中的POST和PUT應該這樣使用:
- POST URI: POST每次都創(chuàng)建新資源窒舟,應該不是冪等的系忙。
POST URI:
?http://www.xxx.com/orders
?http://www.xxx.com/orders/1
- PUT: PUT方法如果資源存在,就更新惠豺,如果不存在就創(chuàng)建 指定的資源银还,所以PUT是冪等的。
PUT URI:
http://www.xxx.com/orders/1