【SpringBoot3】Spring Boot 3.0 集成 Redis 缓存

一、什么是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依赖:

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-data-redis</artifactId>  
</dependency>

2)配置Redis连接

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

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

@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)使用示例

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 的依赖。
<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实现上。

@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 的相关配置中指定这个序列化器。
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

@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、创建测试类

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

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

参考

<think>好的,我现在需要帮助用户解决在Spring Boot 3.0中整合Redis的问题。首先,我应该回想一下Spring Boot 3.0的新特性和与Redis整合的基本步骤。记得Spring Boot 3.0需要Java 17或更高版本,这可能是一个前提条件,用户需要确认他们的环境是否符合要求。 接下来,整合Redis通常需要添加相关的依赖。在Spring Boot 2.x中,常用的依赖是spring-boot-starter-data-redis,但到了3.0,可能依赖的版本号有所变化。需要检查最新的Spring Data Redis文档,确保使用正确的依赖配置。例如,可能需要使用Spring Boot 3.0对应的Spring Data 2022.0.0或更高版本。 然后,配置Redis连接信息。用户需要在application.properties或application.yml文件中设置Redis服务器的主机地址、端口、密码等信息。这里可能会涉及到是否使用lettuce作为默认的连接池,因为Spring Boot从2.x开始默认使用Lettuce而不是Jedis,这一点在3.0中可能继续保持。 接下来是创建配置类,可能涉及到RedisTemplate和StringRedisTemplate的配置。需要确保这些Bean被正确创建,并且序列化方式设置正确,避免出现序列化问题。通常会建议使用Jackson2JsonRedisSerializer来替代默认的JdkSerializationRedisSerializer,以便更友好地处理JSON数据。 然后,用户可能需要编写Repository或者使用RedisTemplate直接操作数据。这里需要给出示例代码,比如如何保存、获取、删除键值对,或者如何使用Hash操作。同时,要提醒用户注意事务管理和管道操作的使用,如果有相关需求的话。 另外,异常处理也是需要考虑的部分。比如连接失败时的处理,或者Redis服务器不可用时的回退机制。可能需要提到Spring的异常处理机制,或者使用@Cacheable等注解时的缓存异常处理。 还有可能涉及到高级功能,比如发布/订阅模式、分布式锁的实现,或者与Spring Cache集成,使用@Cacheable注解来简化缓存逻辑。需要根据用户的具体需求来决定是否展开这些内容。 测试部分也很重要,建议用户编写测试用例,使用@SpringBootTest来验证Redis配置是否正确,数据操作是否如预期。可能需要使用嵌入式Redis服务器进行测试,但注意Spring Boot 3.0是否支持常见的嵌入式Redis库,或者是否需要使用测试容器(Testcontainers)。 最后,需要生成相关问题,可能包括性能优化、集群配置、SSL连接、与其他数据库的整合等,以帮助用户进一步探索。 现在需要确保所有步骤都符合Spring Boot 3.0的最新要求,比如Jakarta EE的包名变更(javax到jakarta),这可能影响到某些配置类或依赖项。同时,检查是否有过时的API或注解,确保示例代码的准确性和兼容性。 可能还需要参考官方文档或可靠的教程,确保提供的信息是最新和正确的。例如,Spring Data Redis的官方文档或Spring Boot的指南,确保依赖项版本和配置示例正确无误。 总结一下,步骤大致是:环境准备、添加依赖、配置连接信息、配置RedisTemplate、编写数据操作代码、异常处理、测试,以及可能的进阶功能。每个步骤都需要详细说明,并给出代码示例,同时注意3.0版本的新变化。</think>在Spring Boot 3.0中整合Redis可通过以下步骤实现,注意新版本对JDK 17和Jakarta EE 9的依赖升级[^1]: ### 步骤1:添加依赖 ```xml <!-- pom.xml --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </dependency> ``` ### 步骤2:配置连接参数 ```properties # application.properties spring.data.redis.host=localhost spring.data.redis.port=6379 spring.data.redis.password=yourpassword spring.data.redis.lettuce.pool.max-active=8 ``` ### 步骤3:配置序列化规则 ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` ### 步骤4:操作示例 ```java @Service public class UserService { @Autowired private RedisTemplate<String, Object> redisTemplate; public void saveUser(User user) { redisTemplate.opsForValue().set("user:" + user.getId(), user); } public User getUser(String userId) { return (User) redisTemplate.opsForValue().get("user:" + userId); } } ``` ### 高级整合:缓存注解 ```java @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } @Service public class ProductService { @Cacheable(value = "products", key = "#id") public Product getProductById(String id) { // 数据库查询逻辑 } } ```
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

顽石九变

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值