第一次從DB中獲取SecKill時(shí),并發(fā)如何處理
按老師視頻的方案,若多個(gè)線程并發(fā)訪問,當(dāng)redis中沒有數(shù)據(jù)時(shí),都會(huì)去請(qǐng)求數(shù)據(jù)庫,然后同時(shí)往redis中寫入相同key的值,請(qǐng)問怎么解?
按老師視頻的方案,若多個(gè)線程并發(fā)訪問,當(dāng)redis中沒有數(shù)據(jù)時(shí),都會(huì)去請(qǐng)求數(shù)據(jù)庫,然后同時(shí)往redis中寫入相同key的值,請(qǐng)問怎么解?
2018-07-05
舉報(bào)
2019-02-26
這個(gè)問題挺好的,確實(shí)會(huì)出現(xiàn)多線程并發(fā)問題,可能會(huì)出現(xiàn)同時(shí)往redis中寫入相同key的值,但是對(duì)結(jié)果沒有影響吧,也可以解決:就是在redis中不存在要去訪問數(shù)據(jù)庫的時(shí)候加上鎖。
2018-07-10
使用互斥鎖(mutex key) ;簡(jiǎn)單點(diǎn)講就是類似“鎖”的機(jī)制,在緩存更新或者過期的情況下,先獲取鎖,在進(jìn)行更新或者從數(shù)據(jù)庫中獲取數(shù)據(jù)后,再釋放鎖,需要一定的時(shí)間等待,就可以從緩存中繼續(xù)獲取數(shù)據(jù)
String get(String key){ ? ?String value = redis.get(key); ? ?if(value == null){ ? ? ? ?if(redis.setnx(key_Mutex),"1"){ ? ? ? ? ? ?redis.expire(key_mutex,3*60);//防止死鎖 ? ? ? ? ? ?value = db.get(key); ? ? ? ? ? ?redis.set(key,value); ? ? ? ? ? ?resdis.delete(key_Mutex); ? ? ? ?}else{ ? ? ? ? ? ?Thread.sleep(50); ? ? ? ? ? ?get(key); ? ? ? ?} ? ?} }