什么是幂等运算?
当前回答
只是想提出一个真实的用例来证明幂等性。在JavaScript中,假设你定义了一堆模型类(就像MVC模型一样)。它的实现方式通常是这样的(基本示例):
function model(name) {
function Model() {
this.name = name;
}
return Model;
}
然后你可以像这样定义新的类:
var User = model('user');
var Article = model('article');
但如果你试图通过模型(' User ')从代码的其他地方获取User类,它会失败:
var User = model('user');
// ... then somewhere else in the code (in a different scope)
var User = model('user');
这两个User构造函数是不同的。也就是说,
model('user') !== model('user');
为了让它是幂等的,你只需要添加一些缓存机制,像这样:
var collection = {};
function model(name) {
if (collection[name])
return collection[name];
function Model() {
this.name = name;
}
collection[name] = Model;
return Model;
}
通过添加缓存,每次你建模('user')它都是同一个对象,所以它是幂等的。所以:
model('user') === model('user');
其他回答
假设客户端向“IstanceA”服务发出请求,该服务处理请求,将其传递给DB,并在发送响应之前关闭。因为客户端没有看到它被处理,它将重试相同的请求。负载均衡器将请求转发到另一个服务实例“InstanceB”,该服务实例将对相同的DB项进行相同的更改。
我们应该使用幂等符号。当客户端向服务发送请求时,它应该有某种类型的请求id,可以保存在DB中,以显示我们已经执行了请求。如果客户端重试请求,“InstanceB”将检查requestId。由于特定的请求已经被执行,因此它不会对DB项进行任何更改。这种请求叫做幂等请求。因此,我们多次发送相同的请求,但不会做任何更改
相当详细和专业的回答。只是添加了一个简单的定义。
幂等=可重复运行
例如, 如果多次执行Create操作,则不能保证运行时没有错误。 但是如果有一个CreateOrUpdate操作,那么它声明了可重运行性(等幂)。
理解幂等运算的一个好例子可能是用远程钥匙锁汽车。
log(Car.state) // unlocked
Remote.lock();
log(Car.state) // locked
Remote.lock();
Remote.lock();
Remote.lock();
log(Car.state) // locked
锁是一个幂等运算。即使每次运行上锁都有一些副作用,比如眨眼,但不管你运行多少次上锁操作,汽车仍然处于相同的上锁状态。
无论调用该操作多少次,结果都是相同的。
幂等操作是一种可以应用多次而不改变结果(即系统状态)的操作、动作或请求,超出初始应用。
示例(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都应该是无效的。
当谈论系统的状态时,我们显然忽略了无害的和不可避免的影响,如日志和诊断。