二十、Elasticsearch演练基于_version进行乐观锁并发控制

1、上机动手实战演练基于_version进行乐观锁并发控制

(1)先构造一条数据

PUT /test_index/test_type/3
{
  "test_field" : "test test"
}

(2)新开个浏览器网页,输入Kibana网址,打开两个Kibana客户端,模拟两个客户端,都获取到了同一条数据
GET /test_index/test_type/3

两个客户端都返回

{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "3",
  "_version": 1,
  "found": true,
  "_source": {
    "test_field": "test test"
  }
}

(3)其中一个客户端,先更新了一下这条数据
同时带上版本号,确保说,es中的数据的版本号,跟客户端中的数据的版本号是相同的才能修改

PUT /test_index/test_type/3?version=1
{
  "test_field" : "test client one"
}

结果

{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "3",
  "_version": 2,
  "result": "updated",
  "_shards": {
    "total": 5,
    "successful": 1,
    "failed": 0
  },
  "created": false
}

结果可看到数据变了,此时版本号是2

(4)另一个客户端,尝试基于version=1的数据进行修改,同样带上version=1(模拟并发请求),进行乐观锁的并发控制

PUT /test_index/test_type/3?version=1
{
  "test_field" : "test client two"
}

结果:

{
  "error": {
    "root_cause": [
      {
        "type": "version_conflict_engine_exception",
        "reason": "[test_type][3]: version conflict, current version [2] is different than the one provided [1]",
        "index_uuid": "ey5OuEyFTHe7QhJUvcLDXQ",
        "shard": "2",
        "index": "test_index"
      }
    ],
    "type": "version_conflict_engine_exception",
    "reason": "[test_type][3]: version conflict, current version [2] is different than the one provided [1]",
    "index_uuid": "ey5OuEyFTHe7QhJUvcLDXQ",
    "shard": "2",
    "index": "test_index"
  },
  "status": 409
}

版本冲突,当前版本是2,要改的1,找不到version=1的数据

(5)在乐观锁成功阻止并发问题之后,尝试正确的完成更新
GET /test_index/test_type/3

结果:

{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "3",
  "_version": 2,
  "found": true,
  "_source": {
    "test_field": "test client one"
  }
}

基于最新的数据和版本号,去进行修改,修改后,带上最新的版本号(这个步骤可能会需要反复执行好几次才能成功,主要看并发量多少)

PUT /test_index/test_type/3?version=2
{
  "test_field" : "test client two"
}

结果:

{
  "_index": "test_index",
  "_type": "test_type",
  "_id": "3",
  "_version": 3,
  "result": "updated",
  "_shards": {
    "total": 5,
    "successful": 1,
    "failed": 0
  },
  "created": false
}

此时version变成了3

若有兴趣,欢迎来加入群,【Java初学者学习交流群】:458430385,此群有Java开发人员、UI设计人员和前端工程师。有问必答,共同探讨学习,一起进步!
欢迎关注我的微信公众号【Java码农社区】,会定时推送各种干货:


qrcode_for_gh_577b64e73701_258.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,322评论 19 139
  • 现在想想,我的症结还是出在妈妈身上,总是感觉她在吸我的精力,而且我不敢背叛,只有我自己发展出一套应对机制才能处理这...
    蹒跚幸福阅读 248评论 0 0
  • 暖冬,可能最冷的温度还没有到来。 不喜欢冬天也不喜欢夏天,只想停留在春天跟秋天,似乎那样的天气跟温度才是最适合人的...
    清风伏笔阅读 422评论 0 1
  • 前几天回家,听我妈说,我妹想要离开现在这份工作,去大城市闯闯。我妈听了后,一脸嫌弃,压根不同意。觉得她现在这份工作...
    soltsolt阅读 369评论 2 2

友情链接更多精彩内容