什么是幂等运算?


当前回答

相当详细和专业的回答。只是添加了一个简单的定义。

幂等=可重复运行

例如, 如果多次执行Create操作,则不能保证运行时没有错误。 但是如果有一个CreateOrUpdate操作,那么它声明了可重运行性(等幂)。

其他回答

无论调用该操作多少次,结果都是相同的。

在计算中,幂等运算是指如果使用相同的输入参数多次调用它,则不会产生额外影响的运算。例如,从集合中移除一项可以被认为是集合上的幂等操作。

在数学中,幂等运算是指f(f(x)) = f(x)。例如,abs()函数是幂等的,因为对于所有x, abs(abs(x)) = abs(x)。

考虑到数学定义中的x代表一个对象的状态,而f是一个可能改变该对象的操作,可以调和这些略有不同的定义。例如,考虑Python集合及其discard方法。discard方法从集合中删除一个元素,如果该元素不存在,则不执行任何操作。所以:

my_set.discard(x)

与执行两次相同的操作具有完全相同的效果:

my_set.discard(x)
my_set.discard(x)

幂等操作经常用于网络协议的设计中,其中执行操作的请求保证至少发生一次,但也可能发生多次。如果操作是幂等的,那么执行两次或两次以上的操作是没有伤害的。

更多信息请参见维基百科关于幂等性的文章。


上面的答案之前有一些不正确和误导性的例子。下面的评论写在2014年4月之前,是指一个较旧的修订。

my 5c: In integration and networking the idempotency is very important. Several examples from real-life: Imagine, we deliver data to the target system. Data delivered by a sequence of messages. 1. What would happen if the sequence is mixed in channel? (As network packages always do :) ). If the target system is idempotent, the result will not be different. If the target system depends of the right order in the sequence, we have to implement resequencer on the target site, which would restore the right order. 2. What would happen if there are the message duplicates? If the channel of target system does not acknowledge timely, the source system (or channel itself) usually sends another copy of the message. As a result we can have duplicate message on the target system side. If the target system is idempotent, it takes care of it and result will not be different. If the target system is not idempotent, we have to implement deduplicator on the target system side of the channel.

简而言之,幂等运算意味着无论你做多少次幂等运算都不会得到不同的结果。

例如,根据HTTP规范的定义,GET、HEAD、PUT、DELETE是幂等操作;但是POST和PATCH不是。这就是为什么有时POST被PUT取代的原因。

幂等性意味着应用一次操作或应用多次操作具有相同的效果。

例子:

乘以0。无论你做多少次,结果仍然是零。 设置布尔标志。不管你做了多少次,旗帜都不会动摇。 从数据库中删除具有给定ID的行。如果你再试一次,排还是消失了。

对于纯函数(没有副作用的函数),幂等性意味着f(x) = f(f(x)) = f(f(f(x)))) = ......)) = f(f(f(f(x)))) = ......))对于x的所有值

对于有副作用的函数,幂等性进一步意味着在第一次应用后不会引起额外的副作用。如果愿意,可以将世界的状态视为函数的附加“隐藏”参数。

请注意,在有并发操作的情况下,您可能会发现您认为是幂等的操作不再是幂等的(例如,在上面的示例中,另一个线程可以取消布尔标志的值)。基本上,当你有并发性和可变状态时,你需要更仔细地考虑幂等性。

在构建健壮系统时,幂等性通常是一个有用的性质。例如,如果存在从第三方接收重复消息的风险,则将消息处理程序用作幂等操作,以便消息效果只发生一次,这是很有帮助的。