二者數(shù)據(jù)同步的關(guān)鍵在于mysql數(shù)據(jù)庫中主鍵,方案是在redis啟動(dòng)時(shí)區(qū)mysql讀取所有表鍵值存入redis中,往redis寫數(shù)據(jù)是,對(duì)redis主鍵自增并進(jìn)行讀取,若mysql更新失敗,則需要及時(shí)清除緩存及同步redis主鍵。參考代碼如下:
String tbname = "login"
;//獲取mysql表主鍵值--redis啟動(dòng)時(shí)long id = MySQL.getID(tbname)
;//設(shè)置redis主鍵值--redis啟動(dòng)時(shí)redisService.set(tbname, String.valueOf(id))
;System.out.println(id)
;long l = redisService.incr(tbname)
;System.out.println(l)
;Login login = new Login()
;login.setId(l)
;login.setName("redis")
;redisService.hmset(String.valueOf(login.getId()), login)
;boolean b = MySQL.insert("insert into login(id,name) values(" + login.getId()+ ",'" + login.getName() + "')")
;/**** 隊(duì)列處理器更新mysql失?。?/p>
** 清除緩存數(shù)據(jù),同時(shí)主鍵值自減*/if (!b){redisService.delKeyAndDecr(tbname, "Login:"+String.valueOf(login.getId()))
;// redisService.delete("Login:"+String.valueOf(login.getId()))
;//redisService.decr(tbname);}System.out.println(redisService.exists("Login:"+String.valueOf(login.getId())));