對(duì)于熱點(diǎn)數(shù)據(jù)(經(jīng)常會(huì)被查詢,但是不經(jīng)常被修改或者刪除的數(shù)據(jù)),首選是使用redis緩存,redis的性能非常優(yōu)秀。
因?yàn)閞edis是內(nèi)存數(shù)據(jù)庫(kù),占用的資源非常珍惜,所以要盡少的存儲(chǔ)redis數(shù)據(jù)。 ? ? ? ? (推薦學(xué)習(xí):Redis視頻教程)
可以通過(guò)設(shè)置緩存的有效期expire,一般是一天的時(shí)間,可以根據(jù)實(shí)際情況調(diào)整,這種方式來(lái)清楚緩存中不常用的數(shù)據(jù)。
代碼中可以這樣設(shè)置:
在存儲(chǔ)redis數(shù)據(jù)的時(shí)候設(shè)置expire,取的時(shí)候重新設(shè)置expire。
如果在過(guò)期時(shí)間內(nèi)沒(méi)有取出該數(shù)據(jù)重新設(shè)置expire的話,那么該redis數(shù)據(jù)就會(huì)清除。
public?TbItem?getTbItemByid(Long?itemid)?{ //添加redis緩存 Jedis?jedis?=??null; try?{ if(itemid?!=?null){ ????jedis?=?jedisPool.getResource(); String?jedisRes?=?jedis.get(ITEM_INFO_KEY+":"+itemid+":BASE"); if(StringUtils.isNotBlank(jedisRes)){ //取redis數(shù)據(jù)的時(shí)候,重新設(shè)置expire jedis.expire(ITEM_INFO_KEY+":"+itemid+":BASE",?ITEM_INFO_KEY_EXPIRE); return?JsonUtils.jsonToPojo(jedisRes,?TbItem.class); } } }?catch?(Exception?e)?{ e.printStackTrace(); }finally{ //關(guān)閉jedis,其實(shí)是還給連接池 jedis.close(); } TbItem?tbItem?=?itemMapper.selectByPrimaryKey(itemid); try?{ if(tbItem!=null){ ????jedis?=?jedisPool.getResource(); jedis.set(ITEM_INFO_KEY+":"+itemid+":BASE",?JsonUtils.objectToJson(tbItem)); //存儲(chǔ)redis數(shù)據(jù)的時(shí)候設(shè)置expire jedis.expire(ITEM_INFO_KEY+":"+itemid+":BASE",?ITEM_INFO_KEY_EXPIRE); } }?catch?(Exception?e)?{ e.printStackTrace(); }finally{ //關(guān)閉jedis,其實(shí)是還給連接池 jedis.close(); } return?tbItem; }
更多Redis相關(guān)技術(shù)文章,請(qǐng)?jiān)L問(wèn)Redis視頻教程欄目進(jìn)行學(xué)習(xí)!
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END