spring boot 缓存redis设置定时过期时间

2年前 (2022) 程序员胖胖胖虎阿
111 0 0

前言

本篇文章分享的就是spring boot中的一个轮子,spring cache注解的方式实现接口数据缓存。默认的配置想非常简单,但是有一个弊端是缓存数据为永久缓存,本次将介绍如何设置接口缓存数据的过期时间

使用redis进行缓存数据,是目前比较常用的缓存解决方案。常用的缓存形式有一下几种:

1.纯原生代码进行redis的增删改查,手工编写缓存工具类,由开发者在代码中进行调用。

        优势:代码由实际使用的开发者进行维护,便于定制化的改造。

2.使用市场上已有的缓存工具,也就是大家常说的大佬的轮子

        优势:方便快捷,提升开发效率

目录

  1. 添加依赖
  2. 添加配置
  3. 常规缓存
  4. 增加设置缓存时间

添加依赖

 修改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中的缓存情况:

spring boot 缓存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 RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, 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(RedisTemplate<String, Object> redisTemplate) {
        return RedisCacheWriter.nonLockingRedisCacheWriter(Objects.requireNonNull(redisTemplate.getConnectionFactory()));
    }

    @Bean
    CacheManager cacheManager(RedisCacheWriter writer) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        Map<String, 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中的数据是被设置了过期时间的

spring boot 缓存redis设置定时过期时间

 此处可能会有个意外惊喜(小坑):就是直接启动程序后,调用接口报错,提示json格式转换异常,这里是由于先前直接用的默认的redisTemplate,value的反序列化问题,可以将之前缓存的数据清理一下,再重新调用就可以了。

总结:

注解方式进行接口数据缓存,在实际项目开发过程中比较常见,我分享的这种方式也是大家比较常用的一种方式,配置简单,开发成本低,使用方便。只需要:

  1. 引入依赖包
  2. 增加redis连接信息
  3. 开启缓存
  4. 添加需要缓存的类或者方法

后记:

这里题外记录一下缓存注解中的一下参数含义及用法

在这里插入图片描述

另外设置缓存的注解中支持spEL表达式,下面是一些可用的表达式含义 

spring boot 缓存redis设置定时过期时间

版权声明:程序员胖胖胖虎阿 发表于 2022年9月1日 下午7:16。
转载请注明:spring boot 缓存redis设置定时过期时间 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...