什么是幂等运算?
当前回答
幂等操作是一种可以应用多次而不改变结果(即系统状态)的操作、动作或请求,超出初始应用。
示例(web应用上下文):
IDEMPOTENT: Making multiple identical requests has the same effect as making a single request. A message in an email messaging system is opened and marked as "opened" in the database. One can open the message many times but this repeated action will only ever result in that message being in the "opened" state. This is an idempotent operation. The first time one PUTs an update to a resource using information that does not match the resource (the state of the system), the state of the system will change as the resource is updated. If one PUTs the same update to a resource repeatedly then the information in the update will match the information already in the system upon every PUT, and no change to the state of the system will occur. Repeated PUTs with the same information are idempotent: the first PUT may change the state of the system, subsequent PUTs should not.
非幂等性: 如果一个操作总是导致状态的变化,比如反复向用户发送相同的消息,导致每次都发送新消息并存储在数据库中,我们称该操作为NON-IDEMPOTENT。
NULLIPOTENT: 如果一个操作没有副作用,就像仅仅在网页上显示信息而没有对数据库进行任何更改(换句话说,你只是在读取数据库),我们说这个操作是NULLIPOTENT。所有get都应该是无效的。
当谈论系统的状态时,我们显然忽略了无害的和不可避免的影响,如日志和诊断。
其他回答
理解幂等运算的一个好例子可能是用远程钥匙锁汽车。
log(Car.state) // unlocked
Remote.lock();
log(Car.state) // locked
Remote.lock();
Remote.lock();
Remote.lock();
log(Car.state) // locked
锁是一个幂等运算。即使每次运行上锁都有一些副作用,比如眨眼,但不管你运行多少次上锁操作,汽车仍然处于相同的上锁状态。
任何操作,每n个结果都会产生与第1个结果值匹配的输出。例如,-1的绝对值是1。-1的绝对值的绝对值是1。-1绝对值的绝对值的绝对值等于1。等等。请参见:什么时候使用递归是非常愚蠢的?
幂等运算可以重复任意次数,结果与只做一次是一样的。在算术中,一个数加零是幂等的。
幂等性在“RESTful”web服务的上下文中被讨论了很多。REST寻求最大限度地利用HTTP来为程序提供对web内容的访问,并且通常与基于soap的web服务进行设置,后者只是在HTTP请求和响应中隐藏远程过程调用样式的服务。
REST将web应用程序组织成“资源”(如Twitter用户或Flickr图像),然后使用POST、PUT、GET和DELETE这些HTTP动词来创建、更新、读取和删除这些资源。
Idempotence plays an important role in REST. If you GET a representation of a REST resource (eg, GET a jpeg image from Flickr), and the operation fails, you can just repeat the GET again and again until the operation succeeds. To the web service, it doesn't matter how many times the image is gotten. Likewise, if you use a RESTful web service to update your Twitter account information, you can PUT the new information as many times as it takes in order to get confirmation from the web service. PUT-ing it a thousand times is the same as PUT-ing it once. Similarly DELETE-ing a REST resource a thousand times is the same as deleting it once. Idempotence thus makes it a lot easier to construct a web service that's resilient to communication errors.
进一步阅读:Richardson和Ruby的RESTful Web服务(幂等性在103-104页讨论),以及Roy Fielding关于REST的博士论文。Fielding是HTTP 1.1 RFC-2616的作者之一,RFC-2616在9.1.2节中讨论了幂等性。
幂等运算即使调用多次也会产生相同状态的结果,前提是传入相同的参数。
幂等操作:多次执行没有副作用的操作。 示例:从数据资源检索值并打印值的操作 非幂等操作:多次执行会造成伤害的操作。(当它们改变某些值或状态时) 示例:从银行账户提款的操作