Spring boot缓存redis实现定时过期有哪些方式
使用redis进行缓存数据,是目前比较常用的缓存解决方案。常用的缓存形式有一下几种:
1.纯原生代码进行redis的增删改查,手工编写缓存工具类,由开发者在代码中进行调用。
优势:代码由实际使用的开发者进行维护,便于定制化的改造。
2.使用市场上已有的缓存工具,也就是大家常说的大佬的轮子
优势:方便快捷,提升开发效率
添加依赖
修改pom文件引入如下配置
?xml version="1.0" encoding="UTF-8"?> project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> modelVersion> 4.0.0/modelVersion> parent> groupId> org.springframework.boot/groupId> artifactId> spring-boot-starter-parent/artifactId> version> 2.7.0/version> relativePath/> !-- lookup parent from repository --> /parent> groupId> com.test/groupId> artifactId> common-project/artifactId> version> 0.0.1-SNAPSHOT/version> name> common-project/name> description> /description> properties> java.version> 1.8/java.version> /properties> dependencies> dependency> groupId> org.springframework.boot/groupId> artifactId> spring-boot-starter/artifactId> /dependency> dependency> groupId> org.springframework.boot/groupId> artifactId> spring-boot-starter-data-redis/artifactId> /dependency> dependency> groupId> org.springframework.boot/groupId> artifactId> spring-boot-starter-web/artifactId> /dependency> dependency> groupId> org.projectlombok/groupId> artifactId> lombok/artifactId> version> 1.18.24/version> /dependency> dependency> groupId> com.alibaba/groupId> artifactId> fastjson/artifactId> version> 2.0.7/version> /dependency> /dependencies> /project>
添加配置
application.yml中增加redisd 配置信息
spring:
redis:
host: localhost
port: 6379
database: 0
password: *****
timeout: 10000
server:
port: 8082
常规缓存
在spring 3.1版本以后,注意是spring的版本,不是spring boot的版本。在spring-context包中合并进去了spring Cache的内容。可以使用注解方式进行缓存设定。
开启缓存
开启缓存只需要在入口函数上增加@EnableCaching注解
@SpringBootApplication @EnableCaching //开启缓存 public class CommonApplication { public static void main(String[] args) { SpringApplication.run(CommonApplication.class,args); } }
设置缓存空间
设置缓存空间可能大家不好理解,换一个通俗的说法就是设置要缓存的类,把这个类下面要缓存的数据的key加上一个统一的前缀,也是一个注解:@CacheConfig这里可以设置具体的值如下
@RestController @RequestMapping("/test") @CacheConfig(cacheNames = "test-controller") public class TestController { @Autowired TestService testService; @RequestMapping("/testCache") @Cacheable(key = "'testCache'",unless = "#result==null") public Object testCache(){ return testService.getUserInfoList(); } }
这里的cacheNames就是我上面说的缓存空间,也许这样还是没办法理解,请看在redis中的缓存情况:
就是说如果我在TestController类下设置的接口缓存数据都会缓存到test-controller这个缓存空间里。
设置缓存
这里就是指具体要缓存的接口数据,使用注解:@Cacheable,具体代码参见上面的代码块。
截止到这里,就可以启动服务,调用接口,会发现数据已经可以缓存到redis中了。但是,这里有一个问题,就是缓存下来的数据,是永久缓存,一旦接口实际的数据有更新,只能通过再设置更新方法来更新缓存,或者删除缓存,我们都知道redis本身是支持设置key的过期时间的,这一特性,让缓存变得更加优雅,所以我们的程序也要有!!!
增加设置缓存过期时间
想要设置缓存过期时间,也并不是很麻烦,只是需要单独增加一个redis的配置类,自定义修改一下缓存管理器就可以了
@Configuration public class RedisCacheManagerConfig { /** * redis模板配置以及序列化配置 * * @param factory 工厂 * @return { @link RedisTemplate} { @link String} , { @link Object} > */ @Bean public RedisTemplateString, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplateString, Object> template = new RedisTemplate> (); template.setConnectionFactory(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); //key 采用的String 的序列化方式 template.setKeySerializer(stringRedisSerializer); //hashde key 也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); //value 序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); //hash 的 value序列化方式采用jackson template.setHashKeySerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); template.afterPropertiesSet(); return template; } @Bean RedisCacheWriter writer(RedisTemplateString, Object> redisTemplate) { return RedisCacheWriter.nonLockingRedisCacheWriter(Objects.requireNonNull(redisTemplate.getConnectionFactory())); } @Bean CacheManager cacheManager(RedisCacheWriter writer) { RedisSerializerString> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); MapString, RedisCacheConfiguration> configurationMap = new HashMap> (); // 配置序列化(解决乱码的问题) RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(1))//time .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); //此处可以自定义缓存空间的缓存的过期时间,可以根据自己实际情况进行设置,也可以不设置,用统一过期时间 configurationMap.put("test-controller", config.entryTtl(Duration.ofSeconds(200))); //解决查询缓存转换异常的问题 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); return RedisCacheManager.builder(writer) .initialCacheNames(configurationMap.keySet()) .withInitialCacheConfigurations(configurationMap) //其他缓存空间缓存过期时间为500S .cacheDefaults(config.entryTtl(Duration.ofSeconds(500))) .build(); } }
增加了此配置类之后,之前的代码均不需要更改,直接启动程序,测试验证,可以看到redis中的数据是被设置了过期时间的
此处可能会有个意外惊喜(小坑):就是直接启动程序后,调用接口报错,提示json格式转换异常,这里是由于先前直接用的默认的redisTemplate,value的反序列化问题,可以将之前缓存的数据清理一下,再重新调用就可以了。
总结
注解方式进行接口数据缓存,在实际项目开发过程中比较常见,我分享的这种方式也是大家比较常用的一种方式,配置简单,开发成本低,使用方便。只需要:
- 引入依赖包
- 增加redis连接信息
- 开启缓存
- 添加需要缓存的类或者方法
后记
这里题外记录一下缓存注解中的一下参数含义及用法
另外设置缓存的注解中支持spEL表达式,下面是一些可用的表达式含义
感谢各位的阅读,以上就是“Spring boot缓存redis实现定时过期有哪些方式”的内容了,通过以上内容的阐述,相信大家对Spring boot缓存redis实现定时过期有哪些方式已经有了进一步的了解,如果想要了解更多相关的内容,欢迎关注网络,网络将为大家推送更多相关知识点的文章。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Spring boot缓存redis实现定时过期有哪些方式
本文地址: https://pptw.com/jishu/652394.html