SpringBoot2整合Redis缓存三步骤代码详解
遵循SpringBoot三板斧
第一步加依赖
org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 2.6.0
第二步写注解
@EnableCaching//开启缓存支持
第三步写配置
spring: redis: database:0 host:192.168.1.11 port:6379 password: timeout:600 lettuce: pool: max-active:50 max-wait:-1 max-idle:8 min-idle:0
编写Redis配置类
/** *@Author:zc *@Date:2019/11/314:12 *@Description:SpringBoot2.0Redis缓存配置 *@EnableCaching:开启缓存支持 */ @Slf4j @Configuration @EnableCaching publicclassRedisConfigextendsCachingConfigurerSupport{ @Value("${sys.dataCaching.expireTime:0}") privateintexpireTime; @Resource privateLettuceConnectionFactorylettuceConnectionFactory; @Override @Bean publicKeyGeneratorkeyGenerator(){//设置自定义key{ClassName+methodName+params} return(target,method,params)->{ StringBuildersb=newStringBuilder(); sb.append(target.getClass().getName()); sb.append(",Method:"); sb.append(method.getName()); sb.append(",Params["); for(inti=0;i{ StringBuildersb=newStringBuilder(); sb.append(target.getClass().getName()); sb.append(",Method:"); sb.append("getById"); sb.append(",Params["); try{ Fieldid=params[0].getClass().getDeclaredField("id"); id.setAccessible(true); sb.append(id.get(params[0]).toString()); }catch(IllegalAccessExceptione){ e.printStackTrace(); }catch(NoSuchFieldExceptione){ e.printStackTrace(); } sb.append("]"); log.debug("DataCachingRedisKey:{}",sb.toString()); returnsb.toString(); }; } //自定义keyGenerator,Key生成器 @Bean publicKeyGeneratordeleteByIdkeyGenerator(){ return(target,method,params)->{ StringBuildersb=newStringBuilder(); sb.append(target.getClass().getName()); sb.append(",Method:"); sb.append("getById"); sb.append(",Params["); for(inti=0;i 0){ log.info("Redis缓存过期时间:{}",expireTime); //设置缓存有效期秒 redisCacheConfiguration.entryTtl(Duration.ofSeconds(expireTime)); }else{ log.info("Redis未设置缓存过期时间"); } returnRedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); } @Bean publicRedisTemplate redisTemplate(RedisConnectionFactoryfactory){//创建RedisTemplate //设置序列化 Jackson2JsonRedisSerializer
如何使用查询缓存
@CacheConfig(cacheNames="demoDao") @Component publicclassDemoDaoimplementsIDemoDAO<>{ @Autowired DemoMappermapper; //用默认配置的keyGenerator @Cacheable @Override publicDemogetById(Integerid){ returnmapper.getById(id); } //使用配置的keyGenerator,清空缓存 @CacheEvict(keyGenerator="updateByIdkeyGenerator") @Override publicintupdate(Tentity){ returnmapper.update(entity); } //使用配置的keyGenerator,清空缓存 @CacheEvict(keyGenerator="deleteByIdkeyGenerator") @Override publicintdeleteById(Integerid){ returnmapper.deleteById(id); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。