21.基于_version进行乐观锁并发控制

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
}

此时修改成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值