1、上機(jī)動(dòng)手實(shí)戰(zhàn)演練基于_version進(jìn)行樂觀鎖并發(fā)控制
(1)先構(gòu)造一條數(shù)據(jù)
PUT /test_index/test_type/3
{
"test_field" : "test test"
}
(2)新開個(gè)瀏覽器網(wǎng)頁,輸入Kibana網(wǎng)址,打開兩個(gè)Kibana客戶端,模擬兩個(gè)客戶端,都獲取到了同一條數(shù)據(jù)
GET /test_index/test_type/3
兩個(gè)客戶端都返回
{
"_index": "test_index",
"_type": "test_type",
"_id": "3",
"_version": 1,
"found": true,
"_source": {
"test_field": "test test"
}
}
(3)其中一個(gè)客戶端,先更新了一下這條數(shù)據(jù)
同時(shí)帶上版本號(hào),確保說,es中的數(shù)據(jù)的版本號(hào),跟客戶端中的數(shù)據(jù)的版本號(hào)是相同的才能修改
PUT /test_index/test_type/3?version=1
{
"test_field" : "test client one"
}
結(jié)果
{
"_index": "test_index",
"_type": "test_type",
"_id": "3",
"_version": 2,
"result": "updated",
"_shards": {
"total": 5,
"successful": 1,
"failed": 0
},
"created": false
}
結(jié)果可看到數(shù)據(jù)變了,此時(shí)版本號(hào)是2
(4)另一個(gè)客戶端,嘗試基于version=1的數(shù)據(jù)進(jìn)行修改,同樣帶上version=1(模擬并發(fā)請(qǐng)求),進(jìn)行樂觀鎖的并發(fā)控制
PUT /test_index/test_type/3?version=1
{
"test_field" : "test client two"
}
結(jié)果:
{
"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
}
版本沖突,當(dāng)前版本是2,要改的1,找不到version=1的數(shù)據(jù)
(5)在樂觀鎖成功阻止并發(fā)問題之后,嘗試正確的完成更新
GET /test_index/test_type/3
結(jié)果:
{
"_index": "test_index",
"_type": "test_type",
"_id": "3",
"_version": 2,
"found": true,
"_source": {
"test_field": "test client one"
}
}
基于最新的數(shù)據(jù)和版本號(hào),去進(jìn)行修改,修改后,帶上最新的版本號(hào)(這個(gè)步驟可能會(huì)需要反復(fù)執(zhí)行好幾次才能成功,主要看并發(fā)量多少)
PUT /test_index/test_type/3?version=2
{
"test_field" : "test client two"
}
結(jié)果:
{
"_index": "test_index",
"_type": "test_type",
"_id": "3",
"_version": 3,
"result": "updated",
"_shards": {
"total": 5,
"successful": 1,
"failed": 0
},
"created": false
}
此時(shí)version變成了3
若有興趣,歡迎來加入群,【Java初學(xué)者學(xué)習(xí)交流群】:458430385,此群有Java開發(fā)人員、UI設(shè)計(jì)人員和前端工程師。有問必答,共同探討學(xué)習(xí),一起進(jìn)步!
歡迎關(guān)注我的微信公眾號(hào)【Java碼農(nóng)社區(qū)】,會(huì)定時(shí)推送各種干貨:
