mysql悲觀鎖和樂觀鎖的理解
1、悲觀鎖
悲觀鎖顧名思意,全部鎖起來
如
select *from t_order where id=101 or id=102 or id=103 for update
通過for update參數,告訴數據庫在讀取where條件中的數據時將這些數據全部鎖住,禁止任何的讀取或者更新操作,其餘操作進入block等待,直接鎖釋放
優點:是能保證數據的一致性
缺點:壞處是所有的查詢都必需等待鎖的或者,如果查詢一多,則數據庫連接一直block,連接數較多,有可能導致數據庫連接超時
2、樂觀鎖
樂觀鎖其實是程序員給悲觀鎖的另一種叫法,事實上是由程序員自己加邏輯處理
如
update t_goods set count = count - ${count} where id=1 count > ${count}
相當於在執行update時,count字段作爲version字段,則此時可保證更新count時,count的數量一定是大於參數${count}的,保證了最大的運行效率,只有在count > ${count}的時候才真正產生衝突
當然也可以用一個獨立的version來作爲標識
如,先查出version,執行完成時更新version+1,如version有衝突則執行失敗
select (status,status,version) from t_goods where id=#{id}
update t_goods
set status=2,version=version+1
where id=#{id} and version=#{version};
優點:此時一般適用於查詢後執行失敗的場景,保證查詢不受鎖的控制
缺點:大併發導致的大規模衝突時會導致較多的失敗回滾操作
MySql悲觀鎖和樂觀鎖的基礎理解
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
Latest Pass Exam With Avaya 31860X Exam Dumps(2022)
declanriver34125
2022-06-20 20:37:57
Databricks Certified Professional Data Scientist Exam Dumps-Easiest Preparation Method(2022)
declanriver34125
2022-06-20 20:23:31
Salesforce Sales Cloud Consultant Practice Test - Best Preparation Material
declanriver34125
2022-06-18 19:23:01
Salesforce Certified Administrator Practice Test - Effective Tips To Pass
declanriver34125
2022-06-18 19:07:55
NBA Finals Game 6 live Free
jeffreycklima
2022-06-17 03:19:12
sdghjkghjgfjhfg
jeffreycklima
2022-06-12 06:25:41
GCP-GC-REP Exam Questions Help You to Score Higher in Your Genesys Exam
jamesconnorx7
2022-06-11 20:09:00
Blood Boost Formula (2022 Update) Customer Complaints & Health Risks?
triciusti
2022-06-10 20:26:25
FWEGESR WAGESR
tahad17me
2022-06-06 15:45:12
Cost-Effective Backup Approach to Promote Backup as a Service Market
reportsfuture24
2022-05-02 17:43:41
Dissertation Writing Services UK
henryrosie890
2022-05-02 16:40:42
Global Probe Card Market segmented By Type (Cantilever Probe Card, MEMS Probe Card, and Vertical Pro
syedsimranskyquest
2022-04-29 00:21:50
Global Hard Seltzer Market Study
manti.manna.skyquestt
2022-04-27 16:17:23