【SpringBoot3】Spring Boot 3.0 集成 Redis 缓存

文章目录

  • 一、什么是redis缓存
  • [二、SpringBoot3 如何集成 Redis](#二、SpringBoot3 如何集成 Redis)
  • [三、spring-boot-starter-cache 结合 Redis 使用](#三、spring-boot-starter-cache 结合 Redis 使用)
    • [1、什么是 spring-boot-starter-cache](#1、什么是 spring-boot-starter-cache)
    • [2、Redis 集成步骤](#2、Redis 集成步骤)
    • 3、使用示例
  • 参考

一、什么是redis缓存

Redis缓存是一个开源的使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。它主要用于作为数据库、缓存和消息中间件,以快速读写和丰富的数据结构支持而著称。

在应用程序和数据库之间,Redis缓存作为一个中间层起着关键作用。通过将常用的数据存储在Redis内存中,可以快速读取,从而避免了从数据库进行复杂的查询操作,减轻了数据库服务器的压力,并提高了应用程序的性能和响应速度。

此外,为了优化热门查询的性能,可以确定希望缓存的查询结果,特别是最常用和最耗时的查询。这样可以进一步提高应用程序的性能和吞吐量。

spring-boot-starter-data-redis默认的Redis客户端是Lettuce。这是因为Lettuce是一个线程安全的、基于Netty通信的Redis客户端,相比之下,Jedis在多线程环境下存在线程安全问题,因此需要增加连接池来解决线程安全的问题,同时可以限制redis客户端的数量。

而Lettuce在多线程环境下不存在线程安全问题,一个连接实例就可以满足多线程环境下的并发访问,当然实例不够的情况下也可以按需增加实例,保证伸缩性。因此,Spring Boot在后续版本中选择了Lettuce作为默认的Redis客户端。

二、SpringBoot3 如何集成 Redis

1)添加依赖

在pom.xml文件中添加Spring Boot Starter Data Redis依赖:

xml 复制代码
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-data-redis</artifactId>  
</dependency>

2)配置Redis连接

在application.properties或application.yml文件中配置Redis连接信息:

properties 复制代码
spring.data.redis.host=127.0.0.1
spring.data.redis.port=6379
spring.data.redis.database=0
spring.data.redis.password=

3)配置 RedisTemplate Bean

java 复制代码
@Configuration  
public class RedisConfig {  
	@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(connectionFactory);
		// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
		Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
		template.setValueSerializer(serializer);
		template.setKeySerializer(new StringRedisSerializer());
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setHashValueSerializer(serializer);
		return template;
	}
}

4)使用示例

java 复制代码
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
public class RedisTemplateTest {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    void test() {
        redisTemplate.opsForValue().set("key_name", "my name is Jacky");
        System.out.println("缓存设置成功");
        String value = (String) redisTemplate.opsForValue().get("key_name");
        System.out.println(value);
    }
}

三、spring-boot-starter-cache 结合 Redis 使用

1、什么是 spring-boot-starter-cache

Spring Boot Starter Cache 是 Spring Boot 体系内提供使用 Spring Cache 的 Starter 包。它可以为你的 Spring Boot 应用提供缓存支持,简化和自动化缓存的配置和识别。通过使用 Spring Cache 的抽象层,开发者可以轻松地使用各种缓存解决方案。

Spring Boot Starter Cache 集成了各种主流缓存实现(ConcurrentMapredisehcacheCaffeine等)

Spring Boot Starter Cache 默认使用ConcurrentMap作为缓存;如果工程中引入了redis配置,则会使用redis作为缓存

Spring Boot Starter Cache 通过CacheManager判断具体使用哪个缓存,每个缓存都有一个具体的CacheManager(比如:EhCacheCacheManagerRedisCacheManagerCaffeineCacheManager),如果没有配置任何的CacheManager,则会使用ConcurrentMap作为缓存

常用注解说明:

名称 说明
@EnableCaching 开启基于注解的缓存
@CacheConfig 统一配置本类的缓存注解的属性
@Cacheable 常用于查询方法,能够根据方法的请求参数对其进行缓存
@CachePut 常用于更新/保存方法,会将方法返回值放入缓存
@CacheEvict 清空缓存

2、Redis 集成步骤

下面是如何在 Spring Boot 应用中使用 spring-boot-starter-cache 与 Redis 进行集成的步骤:

  1. 添加依赖 :
    在你的 pom.xml 文件中添加 spring-boot-starter-cachespring-boot-starter-data-redis 的依赖。
xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置 Redis :

    application.propertiesapplication.yml 文件中配置 Redis 连接信息。

  2. 启用缓存支持 :

    在你的 Spring Boot 主类或配置类上添加 @EnableCaching 注解以启用缓存支持。

  3. 定义缓存配置 :

    你可以创建一个配置类并实现 CacheManagerCustomizer 接口来自定义缓存配置。或者,你可以使用 @EnableCaching 注解并使用属性来定义缓存配置。

    CacheManagerCustomizer是一个Spring框架的接口,它允许用户自定义扩展CacheManager。

    当需要对某个CacheManager实现进行一些自定义时,可以实现CacheManagerCustomizer接口,指定泛型为需要进行自定义的CacheManager实现类,然后把它定义为一个Spring bean。通过实现这个接口,你可以对Spring的CacheManager进行自定义扩展,例如配置缓存策略、设置缓存过期时间等。

    这个接口的使用可以帮助开发者更好地控制和优化缓存的行为,提高应用程序的性能和响应速度。在实现自定义扩展时,可以使用Spring的注解或XML配置来定义自定义逻辑,并根据需要选择是否将自定义的逻辑应用到所有CacheManager实现上,或者只应用到特定的CacheManager实现上。

java 复制代码
@Configuration  
public class CacheConfig {  
    @Bean  
    public CacheManagerCustomizer cacheManagerCustomizer() {  
        return (cacheManager) -> {  
            SimpleKeyGenerator keyGenerator = new SimpleKeyGenerator();  
            keyGenerator.setSalt("some_salt"); //设置盐值,增强安全性  
            cacheManager.getCache("my_cache").setKeyGenerator(keyGenerator); //设置key生成策略  
        };  
    }  
}
  1. 使用缓存注解 :
    在你的服务类中的方法上使用 Spring 的缓存注解,例如 @Cacheable, @CacheEvict, @CachePut 等。这样,当这些方法被调用时,它们将与 Redis 缓存进行交互。
  2. 自定义序列化 :
    如果你需要自定义序列化,你可以创建一个配置类并实现 RedisSerializer 接口。然后,你可以在 Redis 的相关配置中指定这个序列化器。
java 复制代码
private Jackson2JsonRedisSerializer<Object> jacksonSerializer() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
    objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
    return new Jackson2JsonRedisSerializer<>(objectMapper,Object.class);
}

3、使用示例

1、创建测试Service

java 复制代码
@Service
public class MyService {
    @Cacheable(value = "my_cache") //将方法结果缓存到"my_cache"中,key为方法参数的哈希值
    public String getSomeData(String id) throws InterruptedException {
        // 模拟一个耗时操作,比如从数据库中获取数据
        Thread.sleep(1000); //休眠1秒,模拟耗时操作
        return "data for " + id;
    }
}

2、创建测试类

java 复制代码
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.shi9.module.system.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StopWatch;

@Slf4j
@SpringBootTest
public class MyServiceTest {
    @Autowired
    private MyService myService;

    @Test
    public void getData() throws Exception {
        StopWatch stopWatch = new StopWatch("getData");
        stopWatch.start("1");
        System.out.println(myService.getSomeData("k"));
        stopWatch.stop();
        stopWatch.start("2");
        System.out.println(myService.getSomeData("k"));
        stopWatch.stop();
        stopWatch.start("3");
        System.out.println(myService.getSomeData("k"));
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }

}

执行结果如下:

复制代码
data for k
data for k
data for k
StopWatch 'getData': 1.3141034 seconds
----------------------------------------
Seconds       %       Task name
----------------------------------------
1.3104986     100%    1
0.0029345     00%     2
0.0006703     00%     3

可以看见,只有第一次执行耗时,后面两次直接从缓存读取,几乎没有耗时

参考

相关推荐
problc1 小时前
大模型API和秘钥获取地址
数据库·redis·缓存
Antonio9151 小时前
【Redis】Linux 配置Redis
linux·数据库·redis
Antonio9155 小时前
【Redis】 Redis 基础命令和原理
数据库·redis·缓存
半新半旧18 小时前
python 整合使用 Redis
redis·python·bootstrap
daixin884820 小时前
什么是缓存雪崩?缓存击穿?缓存穿透?分别如何解决?什么是缓存预热?
java·开发语言·redis·缓存
daixin88481 天前
Redis过期数据的删除策略是什么?有哪些?
数据库·redis·缓存
fouryears_234171 天前
@PathVariable与@RequestParam的区别
java·spring·mvc·springboot
幻灭行度1 天前
通过redis_exporter监控redis cluster
数据库·redis·缓存
冷崖1 天前
Redis缓存策略以及bigkey的学习(九)
redis·学习·缓存
chen1108____2 天前
用 Docker 一键部署 Flask + Redis 微服务
redis·docker·flask