Home >Database >Redis >Can redis cache hotspot data?

Can redis cache hotspot data?

(*-*)浩
(*-*)浩Original
2019-11-23 10:32:142946browse

Can redis cache hotspot data?

For hot data (data that is often queried, but not often modified or deleted), the first choice is to use redis cache. The performance of redis is very excellent.

Because redis is an in-memory database and the resources it occupies are very precious, so it is necessary to store as little redis data as possible. (Recommended Learning: Redis Video Tutorial )

can be expire by setting the cache's validity period. Generally, it can be adjusted according to the actual situation. Data that is not commonly used.

The code can be set like this:

Set expire when storing redis data, and reset expire when retrieving it.

If the data is not retrieved and reset within the expiration time, the redis data will be cleared.

	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数据的时候,重新设置expire
					jedis.expire(ITEM_INFO_KEY+":"+itemid+":BASE", ITEM_INFO_KEY_EXPIRE);
					return JsonUtils.jsonToPojo(jedisRes, TbItem.class);
					
				}
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//关闭jedis,其实是还给连接池
			jedis.close();
		}
		
		TbItem tbItem = itemMapper.selectByPrimaryKey(itemid);
		
		try {
			if(tbItem!=null){
			    jedis = jedisPool.getResource();
				jedis.set(ITEM_INFO_KEY+":"+itemid+":BASE", JsonUtils.objectToJson(tbItem));
				//存储redis数据的时候设置expire
				jedis.expire(ITEM_INFO_KEY+":"+itemid+":BASE", ITEM_INFO_KEY_EXPIRE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//关闭jedis,其实是还给连接池
			jedis.close();
		}
		
		return tbItem;
	}

For more Redis-related technical articles, please visit the Redis database usage tutorial column to learn!

The above is the detailed content of Can redis cache hotspot data?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn