1空厌、悲觀鎖的簡要說明
基于version的樂觀鎖并發(fā)控制
在數(shù)據(jù)建模,結(jié)合文件系統(tǒng)建模的這個案例拢蛋,把悲觀鎖的并發(fā)控制鳍徽,3種鎖粒度,都給大家仔細講解一下
最粗的一個粒度首昔,全局鎖
/workspace/projects/helloworld
如果多個線程寡喝,都過來,要并發(fā)地給/workspace/projects/helloworld下的README.txt修改文件名
實際上要進行并發(fā)的控制勒奇,避免出現(xiàn)多線程的并發(fā)安全問題预鬓,比如多個線程修改,純并發(fā)赊颠,先執(zhí)行的修改操作被后執(zhí)行的修改操作給覆蓋了
get current version
帶著這個current version去執(zhí)行修改格二,如果一旦發(fā)現(xiàn)數(shù)據(jù)已經(jīng)被別人給修改了,version號跟之前自己獲取的已經(jīng)不一樣了; 那么必須重新獲取新的version號再次嘗試修改
上來就嘗試給這條數(shù)據(jù)加個鎖竣蹦,然后呢顶猜,此時就只有你能執(zhí)行各種各樣的操作了,其他人不能執(zhí)行操作
第一種鎖:全局鎖草添,直接鎖掉整個fs index
2驶兜、全局鎖的上鎖實驗
PUT /fs/lock/global/_create
{}
fs: 你要上鎖的那個index
lock: 就是你指定的一個對這個index上全局鎖的一個type
global: 就是你上的全局鎖對應(yīng)的這個doc的id
_create:強制必須是創(chuàng)建,如果/fs/lock/global這個doc已經(jīng)存在远寸,那么創(chuàng)建失敗抄淑,報錯
利用了doc來進行上鎖
/fs/lock/global /index/type/id --> doc
{
"_index": "fs",
"_type": "lock",
"_id": "global",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
另外一個線程同時嘗試上鎖
PUT /fs/lock/global/_create
{}
{
"error": {
"root_cause": [
{
"type": "version_conflict_engine_exception",
"reason": "[lock][global]: version conflict, document already exists (current version [1])",
"index_uuid": "IYbj0OLGQHmMUpLfbhD4Hw",
"shard": "2",
"index": "fs"
}
],
"type": "version_conflict_engine_exception",
"reason": "[lock][global]: version conflict, document already exists (current version [1])",
"index_uuid": "IYbj0OLGQHmMUpLfbhD4Hw",
"shard": "2",
"index": "fs"
},
"status": 409
}
如果失敗,就再次重復(fù)嘗試上鎖
執(zhí)行各種操作驰后。肆资。。
POST /fs/file/1/_update
{
"doc": {
"name": "README1.txt"
}
}
{
"_index": "fs",
"_type": "file",
"_id": "1",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
DELETE /fs/lock/global
{
"found": true,
"_index": "fs",
"_type": "lock",
"_id": "global",
"_version": 2,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
另外一個線程灶芝,因為之前發(fā)現(xiàn)上鎖失敗郑原,反復(fù)嘗試重新上鎖,終于上鎖成功了夜涕,因為之前獲取到全局鎖的那個線程已經(jīng)delete /fs/lock/global全局鎖了
PUT /fs/lock/global/_create
{}
{
"_index": "fs",
"_type": "lock",
"_id": "global",
"_version": 3,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
POST /fs/file/1/_update
{
"doc": {
"name": "README.txt"
}
}
{
"_index": "fs",
"_type": "file",
"_id": "1",
"_version": 3,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
DELETE /fs/lock/global
3犯犁、全局鎖的優(yōu)點和缺點
優(yōu)點:操作非常簡單,非常容易使用女器,成本低
缺點:你直接就把整個index給上鎖了酸役,這個時候?qū)ndex中所有的doc的操作,都會被block住,導(dǎo)致整個系統(tǒng)的并發(fā)能力很低
上鎖解鎖的操作不是頻繁涣澡,然后每次上鎖之后贱呐,執(zhí)行的操作的耗時不會太長,用這種方式入桂,方便