Get the App
SLTechnology News&Howtos  ›  Database  › 

The method of caching Hot spot data in redis

Shulou Source: shulou.com Published: 2022-06-01 15:25:16 10月28日 Update

This article will explain in detail the method of redis caching hot data for everyone. Xiaobian thinks it is quite practical, so share it with you for reference. I hope you can gain something after reading this article.

For hot data (data that is frequently queried but not frequently modified or deleted), redis caching is preferred, and redis performs very well.

Because redis is an in-memory database, the resources it occupies are very precious, so store redis data as little as possible.

You can set the expiration date of the cache, usually one day, which can be adjusted according to the actual situation. This way to clear the data that is not commonly used in the cache.

The code can be set like this:

Set expire when storing redis data and reset expire when fetching.

If the data is not retrieved and reset within the expiration time, the redis data is erased.

public TbItem getTbItemByid(Long itemid) { //Add redis cache Jedis jedis = null; try { if(itemid != null){ jedis = jedisPool.getResource(); String jedisRes = jedis.get(ITEM_INFO_KEY+":"+itemid+":BASE"); if(StringUtils.isNotBlank(jedisRes)){ //reset expire when fetching redis data jedis.expire(ITEM_INFO_KEY+":"+itemid+":BASE", ITEM_INFO_KEY_EXPIRE); return JsonUtils.jsonToPojo(jedisRes, TbItem.class); } } } catch (Exception e) { e.printStackTrace(); }finally{ //close jedis, actually return to the connection pool jedis.close(); } TbItem tbItem = itemMapper.selectByPrimaryKey(itemid); try { if(tbItem!= null){ jedis = jedisPool.getResource(); jedis.set(ITEM_INFO_KEY+":"+itemid+":BASE", JsonUtils.objectToJson(tbItem)); //set expire when storing redis data jedis.expire(ITEM_INFO_KEY+":"+itemid+":BASE", ITEM_INFO_KEY_EXPIRE); } } catch (Exception e) { e.printStackTrace(); }finally{ //close jedis, actually return to the connection pool jedis.close(); } return tbItem; } About redis cache hot data method to share here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Tags: Data cache time hot spots storage methods time more articles good excellent practical effective clear code memory content can be passed actually often Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple MySQL Docker Xiaomi Linux