22基于external version进行乐观锁并发控制
external version简介
es提供一个feature,可以不用它提供的内部version版本号来进行并发控制,可以基于你自己维护的一个版本号来进行并发控制。例如:加入你的数据在mysql里也有一份,然后你的系统本身就维护了一个版本号,不管怎么生成的,程序控制的。此时,你进行乐观锁并发控制的时候,可能并不是想要用es内部的——version来进行控制,而是用你自己维护的那个version来进行控制。
?version=1
?version=1&version_type=external
version_type=external,唯一的区别在于,_version,只有当你提供的version与es中的_version一模一样的时候,才可以进行修改,只要不一样,就报错;当version_type=external的时候,只有当你提供的version比es中的_version大的时候,才能完成修改
es,_version=1,?version=1,才能更新成功
es,_version=1,?version>1&version_type=external,才能成功,比如说?version=2&version_type=external
1.先构造一条数据:
PUT /test_index/test_type/8
{
"test_fild":"test external version"
}
{
"_index": "test_index",
"_type": "test_type",
"_id": "8",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 0,
"_primary_term": 1
}
2.模拟两个客户端同时查询这条数据
GET test_index/test_type/8
{
"_index": "test_index",
"_type": "test_type",
"_id": "8",
"_version": 1,
"found": true,
"_source": {
"test_fild": "test external version"
}
}
3.第一个客户先进行修改
此时客户端程序是在自己的数据库中获到了这条数据的最新版本号,比如说2
PUT /test_index/test_type/8?version=2&version_type=external
{
"test_fild":"test external version 1"
}
{
"_index": "test_index",
"_type": "test_type",
"_id": "8",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}
4.模拟第二个客户端修改
第二个客户在数据库中拿到的数据版本为2,同时基于version=2发起修改。
PUT /test_index/test_type/8?version=2&version_type=external
{
"test_fild": "test external version 2"
}
{
"error": {
"root_cause": [
{
"type": "version_conflict_engine_exception",
"reason": "[test_type][7]: version conflict, current version [3] is higher or equal to the one provided [2]",
"index_uuid": "wQZgA5-ZTUGDo8B9rH77cQ",
"shard": "3",
"index": "test_index"
}
],
"type": "version_conflict_engine_exception",
"reason": "[test_type][7]: version conflict, current version [3] is higher or equal to the one provided [2]",
"index_uuid": "wQZgA5-ZTUGDo8B9rH77cQ",
"shard": "3",
"index": "test_index"
},
"status": 409
}
此时版本号不匹配 从新获取external的版本号。从新提交。
PUT /test_index/test_type/8?version=3&version_type=external
{
"test_fild": "test external version 2"
}
{
"_index": "test_index",
"_type": "test_type",
"_id": "8",
"_version": 3,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 2,
"_primary_term": 1
}