什么是幂等运算?
当前回答
幂等运算即使调用多次也会产生相同状态的结果,前提是传入相同的参数。
其他回答
无论调用该操作多少次,结果都是相同的。
任何操作,每n个结果都会产生与第1个结果值匹配的输出。例如,-1的绝对值是1。-1的绝对值的绝对值是1。-1绝对值的绝对值的绝对值等于1。等等。请参见:什么时候使用递归是非常愚蠢的?
简而言之,幂等运算意味着无论你做多少次幂等运算都不会得到不同的结果。
例如,根据HTTP规范的定义,GET、HEAD、PUT、DELETE是幂等操作;但是POST和PATCH不是。这就是为什么有时POST被PUT取代的原因。
幂等操作是一种可以应用多次而不改变结果(即系统状态)的操作、动作或请求,超出初始应用。
示例(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都应该是无效的。
当谈论系统的状态时,我们显然忽略了无害的和不可避免的影响,如日志和诊断。
对集合的幂等运算在应用一次或多次时,其成员保持不变。
它可以是像absolute(x)这样的一元运算,其中x属于一组正整数。这里absolute(absolute(x)) = x。
它可以是一个二进制操作,比如集合与自身的并集总是返回相同的集合。
干杯