看到了一篇講幂等性的文章,我認為把幂等性說得十厘清楚。如果你像我一樣對幂等性還有困惑,可以仔細看下這篇文章。原文位址:
https://www.restapitutorial.com/lessons/idempotency.html【英文原文】
Idempotence is a funky word that often hooks people. Idempotence is sometimes a confusing concept, at least from the academic definition.
From a RESTful service standpoint, for an operation (or service call) to be idempotent, clients can make that same call repeatedly while producing the same result. In other words, making multiple identical requests has the same effect as making a single request. Note that while idempotent operations produce the same result on the server (no side effects), the response itself may not be the same (e.g. a resource's state may change between requests).
The PUT and DELETE methods are defined to be idempotent. However, there is a caveat on DELETE. The problem with DELETE, which if successful would normally return a 200 (OK) or 204 (No Content), will often return a 404 (Not Found) on subsequent calls, unless the service is configured to "mark" resources for deletion without actually deleting them. However, when the service actually deletes the resource, the next call will not find the resource to delete it and return a 404. However, the state on the server is the same after each DELETE call, but the response is different.
GET, HEAD, OPTIONS and TRACE methods are defined as safe, meaning they are only intended for retrieving data. This makes them idempotent as well since multiple, identical requests will behave the same.
【為了友善,我翻譯一下】
“幂等性”是一個經常引人注意的時髦時彙。同時“幂等性”有時也是一個令人很困惑的慨念(至少從其學術定義來看)。
從RESTful服務的角度來說,如果一個operation(或service call)是幂等的,那麼用戶端以相同的方式重複調用服務就應該産生相同的結果。換句話說,發出多個相同的請求,與發出單個請求具有相同的效果。需要注意的是,雖然幂等性操作會在伺服器端産生相同的結果(沒有副作用),但操作的response本身可能并不相同(比如資源狀态會在不同請求之間發生變化)。
PUT和DELETE方法被定義為幂等的。DELETE操作要特别注意的一個問題是,DELETE操作成功通常會傳回200(OK)或204(No Content),但後續相同的DELETE操作可能會傳回404(Not Found),除非服務被配置成隻标記資源的删除狀态而不是真正地删除資源。但是,當服務實際上已删除指定資源時,後續DELETE調用就會找不到該資源,并傳回404。多次DELETE調用之後,伺服器端的狀态是相同的,但傳回可以不同。
GET、HEAD、OPTIONS和TRACE方法被定義成安全的,意味着它們隻是為了擷取資料,多個相同請求時伺服器端的表現是相同的,是以它們是天然幂等的。
[感想]
幂等性不同于傳回值。