锁的简单分类
顾名思义,就算很悲观,每次去拿数据的时候都认为别人会修改,所以在每次拿到数据的时候都会上锁,这样别人想拿到这个数据就会阻塞,直到它拿到锁。传统的关系型数据库里面就用到了很多这种锁机制,比如行锁、表锁、读锁、写锁等,都是在做操作之前先上锁。
顾名思义,就算很乐观,每次去拿数据的时候都认为别人不会修改,所以不会上锁,但是在更新的时候会判断一下在此期间别人有没有去更新这个数据,比如可以使用版本号等机制。乐观锁适用于多读的应用类型,这样可以提高吞吐量,因为我们elasticsearch一般业务场景都是写少读多,所以通过乐观锁可以在控制并发的情况下又能有效的提高系统吞吐量。
1、elasticsearch中对文档的index,GET和DELETE请求时候,都会返回一个_version,当文档被修改时版本号递增 2、所有文档的更新或删除API,都可以介绍version参数,这允许你在代码中使用乐观的并发控制,这里要注意的时版本号要大于旧的版本号,并且加上version_type=external
获取文档
curl -X GET "http://47.93.35.38:9200/nba/_doc/1"
返回结果
{
"_index": "nba",
"_type": "_doc",
"_id": "1",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"found": true,
"_source": {
"name": "张三",
"team_name": "火箭",
"position": "前锋",
"play_year": "10",
"jerso_no": "13"
}
}
可以看到当前的_version等于1
我们通过版本号去修改数据
curl -X PUT "http://47.93.35.38:9200/nba/_doc/1?version=1&version_type=external" -H 'Content-Type:application/json' -d '
{
"name":"张三1",
"team_name":"火箭",
"position":"前锋",
"play_year":"10",
"jerso_no":"13"
}
'
返回结果
{
"error": {
"root_cause": [
{
"type": "version_conflict_engine_exception",
"reason": "[1]: version conflict, current version [1] is higher or equal to the one provided [1]",
"index_uuid": "m_z801WySBCVX-ujrGSv8g",
"shard": "2",
"index": "nba"
}
],
"type": "version_conflict_engine_exception",
"reason": "[1]: version conflict, current version [1] is higher or equal to the one provided [1]",
"index_uuid": "m_z801WySBCVX-ujrGSv8g",
"shard": "2",
"index": "nba"
},
"status": 409
}
可以看到报错了,因为我们在进行修改等操作时,版本号要大于当前版本号才行
修改版本号在进行修改
curl -X PUT "http://47.93.35.38:9200/nba/_doc/1?version=2&version_type=external" -H 'Content-Type:application/json' -d '
{
"name":"张三1",
"team_name":"火箭",
"position":"前锋",
"play_year":"10",
"jerso_no":"13"
}
'
返回结果
{
"_index": "nba",
"_type": "_doc",
"_id": "1",
"_version": 2,
"result": "updated",
"_shards": {
"total": 3,
"successful": 3,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}
修改成功,并且返回了当前文档的版本号
再次查看数据
curl -X GET "http://47.93.35.38:9200/nba/_doc/1"
返回结果
{
"_index": "nba",
"_type": "_doc",
"_id": "1",
"_version": 2,
"_seq_no": 1,
"_primary_term": 1,
"found": true,
"_source": {
"name": "张三1",
"team_name": "火箭",
"position": "前锋",
"play_year": "10",
"jerso_no": "13"
}
}
数据也被正常修改
|