elasticsearch基于_version进行乐观锁并发控制
es版本elasticsearch-6.2.4
kibana版本:kibana-6.2.4-windows-x86_64
1.构造一条数据
PUT /test_index/test_type/7
{
"test_fild":"test_test"
}
kibana返回结果:
{
"_index": "test_index",
"_type": "test_type",
"_id": "7",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 0,
"_primary_term": 1
}
2.模拟两个客户端都获取同一条数据
此时开两个kibana客户端都获取id为7的这条数据:
GET test_index/test_type/7
{
"_index": "test_index",
"_type": "test_type",
"_id": "7",
"_version": 1,
"found": true,
"_source": {
"test_fild": "test_test"
}
}
3.其中一个客户端新更新一条数据
该客户端更新数据同时带上版本号(_version),确保es中的版本号跟客户端中的数据版本号是相同的才能修改。
PUT /test_index/test_type/7?version=1
{
"test_fild":"test_test_onechenge"
}
返回数据
{
"_index": "test_index",
"_type": "test_type",
"_id": "7",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}
此时数据version已经为2(更新成功)
4.另外一个客户端尝试基于version=1进行修改
该客户端更新数据同时带上版本号(_version),确保es中的版本号跟客户端中的数据版本号是相同的才能修改。
PUT /test_index/test_type/7?version=1
{
"test_fild":"test_test_twochange"
}
返回错误结果:
{
"error": {
"root_cause": [
{
"type": "version_conflict_engine_exception",
"reason": "[test_type][7]: version conflict, current version [2] is different than the one provided [1]",
"index_uuid": "wQZgA5-ZTUGDo8B9rH77cQ",
"shard": "3",
"index": "test_index"
}
],
"type": "version_conflict_engine_exception",
"reason": "[test_type][7]: version conflict, current version [2] is different than the one provided [1]",
"index_uuid": "wQZgA5-ZTUGDo8B9rH77cQ",
"shard": "3",
"index": "test_index"
},
"status": 409
}
由于在第三步已经修改es数据版本号为2了所以此时无法进行数据修改。
5.乐观锁成功阻止并发后,尝试正确的完成更新
GET test_index/test_type/7
{
"_index": "test_index",
"_type": "test_type",
"_id": "7",
"_version": 2,
"found": true,
"_source": {
"test_fild": "test_test_onechenge"
}
}
基于最新的数据和版本号,进行修改,修改后,带上最新版本号进行修改。
PUT /test_index/test_type/7?version=2
{
"test_fild": "test_test_twochenge"
}
{
"_index": "test_index",
"_type": "test_type",
"_id": "7",
"_version": 3,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 2,
"_primary_term": 1
}
此时修改成功。