redis與mysql資料同步

來源:互聯網
上載者:User

標籤:

應用Redis實現資料的讀寫,同時利用隊列處理器定時將資料寫入mysql,此種情況存在的問題主要是如何保證mysql與redis的資料同步,

二者資料同步的關鍵在於mysql資料庫中主鍵,方案是在redis啟動時去mysql讀取所有表索引值存入redis中,往redis寫資料時,對redis主

鍵自增並進行讀取,若mysql更新失敗,則需要及時清除緩衝及同步redis主鍵。

 1 String tbname = "login"; 2          3 //擷取mysql表主索引值--redis啟動時 4 long id = MySQL.getID(tbname); 5 //設定redis主索引值--redis啟動時 6 redisService.set(tbname, String.valueOf(id)); 7  8 System.out.println(id); 9 long l = redisService.incr(tbname);10 System.out.println(l);11 Login login = new Login();12 login.setId(l);13 login.setName("redis");14 redisService.hmset(String.valueOf(login.getId()), login);15 16 boolean b = MySQL.insert("insert into login(id,name) values(" + login.getId() + ",‘" + login.getName() + "‘)");17 /**18  * 19  * 隊列處理器更新mysql失敗:20  * 21  * 清除快取資料,同時主索引值自減22  */23 if (!b){24     redisService.delKeyAndDecr(tbname, "Login:"+String.valueOf(login.getId()));25 }26 System.out.println(redisService.exists("Login:"+String.valueOf(login.getId())));27 System.out.println(redisService.get(tbname));28 複製代碼

 

redis與mysql資料同步

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.