spring boot使用redis缓存数据与自动清除

在spring boot项目中使用缓存很方便,有如下两种使用场景:

  1. 直接操作RedisTemplate缓存数据
  2. 在方法上加@Cacheable注解来缓存数据

方法1适用于缓存session、token等用户登录信息

方法2适用于缓存查询结果

直接操作RedisTemplate能够很灵活的对存入缓存中的key与value做定制化、并能很容易的实现缓存对象的过期时间。用@Cacheable注解方式的话,是不支持设置TTL,也就是说没有直接的方式设置缓存对象的过期时间,那么怎样才能实现缓存对象的自动清除呢?别着急,接着看。

 

一、pom配置,要加入对spring-boot-starter-cache与spring-boot-starter-data-redis的依赖

 
       org.springframework.boot
        spring-boot-starter-parent
        2.0.3.RELEASE
    

   
   	
		org.springframework.boot
		spring-boot-starter
	
		
        
        
		org.springframework.boot
		spring-boot-starter-cache
	
        
    		org.springframework.boot
    		spring-boot-starter-data-redis
	
	
 		org.apache.commons
 		commons-pool2
 		2.0
	
        
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        

        
        
	    com.zaxxer
	    HikariCP
            3.1.0
	

        
        
		org.postgresql
		postgresql
		42.1.1
	

        

        
        
            com.alibaba
            fastjson
            1.2.32
        
    

二、写个RedisCacheConfig文件,扩展CachingConfigurerSupport。缓存的自动清除有cacheEvict方法注解实现。

@Configuration
@EnableCaching
@EnableScheduling
public class RedisCacheConfig extends CachingConfigurerSupport{
	
	private static final Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class);
	
	@Resource
	private LettuceConnectionFactory lettuceConnectionFactory;
	
	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, Method method, Object... params) {
				StringBuffer sb = new StringBuffer();
				sb.append(target.getClass().getName());
				sb.append(method.getName());
				for (Object obj : params) {
					sb.append(obj.toString());
				}
				return sb.toString();
			}
		};
	}


	@Bean
        public CacheManager cacheManager(){
		RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
				.fromConnectionFactory(lettuceConnectionFactory);
		@SuppressWarnings("serial")
		Set cacheNames = new HashSet() {
			{
				add("apiCache");
				add("dictDataCache");
				add("manufacturedGood");
				add("rawMaterial");
			}
		};
         
           builder.initialCacheNames(cacheNames);
		
		   return builder.build();
        }
	
	@CacheEvict(allEntries = true, cacheNames = { "manufacturedGood", "rawMaterial"})
	@Scheduled(fixedDelay = 60*1000)
	public void cacheEvict() {
		logger.info("[RedisCacheConfig][cacheEvict] start to clear cache");
	}
	
	
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory){
    	Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(
				Object.class);
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
	        om.enableDefaultTyping(DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(om);

		RedisTemplate redisTemplate = new RedisTemplate();
		redisTemplate.setConnectionFactory(lettuceConnectionFactory);
		RedisSerializer stringSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(stringSerializer);
		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
		redisTemplate.setHashKeySerializer(stringSerializer);
		redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
		redisTemplate.afterPropertiesSet();
		
		return redisTemplate;
    }
} 
  

说明:

  1. 在class上面需要加上@EnableCaching与@EnableScheduling注解
  2. cacheEvict()方法就是实现缓存对象的自动清除的地方,@CacheEvict注解指明cacheNames中指定的缓存,allEntries = true表示清除每个缓存中的所有实体。@Scheduled指定以何种方式触发这个清除动作,fixedDelay = 60*1000 表明上次执行完毕后间隔1分钟清除一次。注意单位是毫秒。当然,还有其它的方式,比如fixedRate,cron等

三、通过@Cacheable自动缓存数据

@Service
public class RawMaterialQueryServiceImpl implements RawMaterialQueryService {
	
	@Autowired
	private RawMaterialDao rawMaterialDao;

	@Override
	@Cacheable(cacheNames="rawMaterial",sync=true, key="'RawMaterialID'.concat(#p0)")
	public RawMaterial getById(Integer id) {
		if(null == id) {
			return null;
		}
		Optional optional = rawMaterialDao.findById(id);
		return optional.isPresent()?optional.get():null;
	}

}

说明:

     在getById这个方法上的@Cacheable注解对查询结果做缓存,将查询的结果缓存到rawMaterial中,key为固定前缀RawMaterialID加上查询参数id。sync=true,多线程用相同的id调用此方法,如果没有命中,只有一个线程会调用方法中的查询动作,其它线程会等待。

四、直接调用。写个辅助类,直接操作RedisTemplate。在put对象时,可以直接指定过期时间。

@Component
public class RedisUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
	
	private static final String FRONT_END_SESSION_CACHE_PREFIX = "FE_SESS_";
	private static final String BACK_END_SESSION_CACHE_PREFIX = "BE_SESS_";
	private static final String LOCALE_CACHE_PREFIX = "LOCALE_";
	
	@Value("${cache.redis.defaultlocale}")
	private String defaultLocale;
	
	@Value("${cache.redis.session.backend.expiretime}")
	private int beSessionExpireTime;
	
	@Value("${cache.redis.session.frontend.expiretime}")
	private int feSessionExpireTime;

	@Resource
        private RedisTemplate redisTemplate;
	
	public void cacheFrontEndSession(String sessionId,Integer userId) {
		if(StringUtil.assertNull(sessionId)) {
			return;
		}
		putWithTimeout(FRONT_END_SESSION_CACHE_PREFIX+sessionId, userId,feSessionExpireTime);
	}
	
	public boolean removeFrontEndSession(String sessionId) {
		if(StringUtil.assertNull(sessionId)) {
			return true;
		}
		return delete(FRONT_END_SESSION_CACHE_PREFIX+sessionId);
	}
	
	public Integer getFrontEndSessionCache(String sessionId) {
		try {
			Object value = get(FRONT_END_SESSION_CACHE_PREFIX+sessionId);
			if(null != value) {
				putWithTimeout(FRONT_END_SESSION_CACHE_PREFIX+sessionId, value,feSessionExpireTime);
				return Integer.parseInt(value+"");
			}else {
				return null;
			}
			
		}catch(Exception e) {
			return null;
		}
	}
	
	public void cacheBackEndSession(String sessionId,Integer userId) {
		if(StringUtil.assertNull(sessionId)) {
			return;
		}
		putWithTimeout(BACK_END_SESSION_CACHE_PREFIX+sessionId, userId,beSessionExpireTime);
	}
	
	public boolean removeBackEndSession(String sessionId) {
		if(StringUtil.assertNull(sessionId)) {
			return true;
		}
		return delete(BACK_END_SESSION_CACHE_PREFIX+sessionId);
	}
	
	public Integer getBackEndSessionCache(String sessionId) {

		try {
			Object value = get(BACK_END_SESSION_CACHE_PREFIX+sessionId);
			if(null != value) {
				putWithTimeout(BACK_END_SESSION_CACHE_PREFIX+sessionId, value,beSessionExpireTime);
				return Integer.parseInt(value+"");
			}else {
				return null;
			}
			
		}catch(Exception e) {
			return null;
		}
	}
	
	public void cacheLocale(Integer userId,String locale) {
		if(null == userId) {
			return;
		}
		put(LOCALE_CACHE_PREFIX+userId, locale);
	}
	
	public String getLocaleCache(Integer userId) {
		try {
			return (String)get(LOCALE_CACHE_PREFIX+userId);
		}catch(Exception e) {
			return null;
		}
	}
	
	private void put(Object key,Object value) {
		redisTemplate.opsForValue().set(key, value);
	}
	
	private void putWithTimeout(Object key,Object value,long timeout) {
		redisTemplate.opsForValue().set(key, value,timeout,TimeUnit.SECONDS);
	}
	
	private Object get(Object key) {
		if(null == key) {
			return null;
		}
		return redisTemplate.opsForValue().get(key);
	}
	
	private boolean delete(Object key) {
		if(null == key) {
			return true;
		}
		return redisTemplate.delete(key);
	}

	public String getDefaultLocale() {
		return defaultLocale;
	}
	
}

五、配置文件application.properties

#=====================redis config================================
spring.cache.type=redis
spring.redis.host=192.168.1.252
spring.redis.port=6379
spring.redis.password=xxxxx
spring.redis.database=0
spring.redis.timeout=5000
spring.redis.lettuce.pool.max-idle=50
spring.redis.lettuce.pool.min-idle=10
spring.redis.lettuce.pool.max-active=-1
spring.redis.lettuce.pool.max-wait=-1
cache.redis.defaultlocale=zh_CN
#session过期时间,单位:秒
cache.redis.session.backend.expiretime=300
cache.redis.session.frontend.expiretime=3600

 

 

总结, 通过上述步骤,展示了在spring boot项目中同时使用通过操作RedisTemplate和@Cacheable的方式来缓存数据,并实现缓存的自动清除功能。

 

 

你可能感兴趣的:(spring,redis)