本文主要是介绍Spring Cache+Redis缓存数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Spring Cache缓存组件,提供了类似@Transactional注解事务的注解Cache支持,且提供了Cache等抽象,方便切换各种底层Cache(比如Redis)
一、添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency><!--Spring2.x集成redis所需要的-->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
</dependency>
二、Redis配置类
@Configuration
@EnableCaching
public class RedisConfig{/**自定义key规则*/@Beanpublic KeyGenerator keyGenerator(){return new KeyGenerator(){@Overridepublic Object generate(Object target,Method method,Object... params){StringBuilder sb = new StringBuilder();sb.append(target.getClass().getName());sb.append(method.getName());for(Object obj:params){sb.append(obj.toString());}return sb.toString();}}}/**设置redisTemplate规则*/@Beanpublic RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);//解决查询缓存转换异常的问题ObjectMapper om = new ObjectMapper();//指定要序列化的域om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);//序列号key valueredisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}/**设置CacheManager缓存规则*/@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory){RedisSerializer<String> redisSerializer = new StringRedisSerializer();Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);//解决查询缓存转换异常的问题ObjectMapper om = new ObjectMapper();//指定要序列化的域om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);//配置序列化(解决乱码问题),过期时间600秒RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(600)).serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).disableCachingNullValues();RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).build();return cacheManager;}
}
三、添加配置(application.properties)
spring.redis.host=192.168.44.165
spring.redis.port=6379
spring.redis.database=0
spring.redis.timeout=1800000spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0
服务器中通过命令启动redis
cd /usr/local/bin
./redis-server /etc/redis.confps -ef | grep redis #查看是否启动成功# 进入客户端,操作redis
./redis-cli
四、使用注解操作
①、@Cacheable 根据方法对其返回结果进行缓存,下次请求时,如果缓存存在,则直接读取缓存数据
如果缓存不存在,则执行方法,并把返回结果放入缓存,一般用在查询方法上
value 缓存名,必填,制定了缓存存放在哪块命名空间
cacheNames与value差不多,二选一即可
key 可选属性,使用SpEL标签自定义缓存的key
/**ServiceImpl实现类上的方法中
*/
@Cacheable(value="dict",keyGenerator="keyGenerator")//根据类名、包名生成的key,key前缀为dict
@Override
public List<Dict> findByParantId(Long parentId){List<Dict> dictList = dictMapper.selectList(new QueryWrapper<Dict>().eq("parent_id",parentId));dictList.stream().forEach(dict -> {boolean isHasChildren = this.isHasChildren(dict.getId());dict.setHasChileren(isHasChildren);});return dictList;
}
②、@CachePut使用该注解标志的方法,每次都会执行,并将结果存入指定缓存中
其他方法可以直接从相应的缓存中读取数据,而不需要查询数据库,一般用在新增方法上
value 缓存名,必填,制定了缓存存放在哪块命名空间
cacheNames与value差不多,二选一即可
key 可选属性,使用SpEL标签自定义缓存的key
③、@CacheEvict 清空缓存中的内容,一般用在更新或删除方法上
value 缓存名,必填,制定了缓存存放在哪块命名空间
cacheNames与value差不多,二选一即可
key 可选属性,使用SpEL标签自定义缓存的key
@CacheEvict(value="dict",allEntries=true) //方法调用后,清空所有缓存
@Override
public void importData(MultipartFile file){ExcelHelper fileHelper = new ExcelHelper(DictEeVo.class);List<DictEeVo> dictVoList = fileHelper.importExcel(file);if(!CollectionUtils.isEmpty(dictVoList)){dictMapper.imsertBatch(dictVoList);}
}
这篇关于Spring Cache+Redis缓存数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!