前言
通过在SpringBoot中集成Redis,详细梳理集成过程。包括SpringBoot启动过程中,容器的刷新、自动配置的流程、各类注解的处理。
类比在纯Spring中集成Redis,体验SpringBoot自动配置给开发带来了哪些便利。
一、测试样例
1.1配置文件
application.yml
spring:
redis:
host: *.*.*.*
port: 6379
password: 123456
database: 0
timeout: 1000
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
1.2依赖项
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
SpringBoot中默认自带了Redis客户端lettuce
1.3单元测试类
package com.lazy.snail;
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;
import org.springframework.data.redis.core.StringRedisTemplate;
@SpringBootTest
class ApplicationTests {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
void contextLoads() {
stringRedisTemplate.opsForValue().set("name", "lazysnail");
stringRedisTemplate.opsForValue().set("email", "lazy_snail@aliyun.com");
}
}
- 测试结果:
二、自动配置机制版本差异
Spring Boot自2.7版本开始逐步弃用spring.factories文件,并在3.0版本中将其彻底移除。
2.1SpringBoot2.7版本前
在/META-INF/目录下,包含了一系列的自动配置类,这些类可以在满足特定条件时被Spring Boot自动加载和使用。
2.2SpringBoot2.7.x版本
/META-INF/spring目录下新增了org.springframework.boot.autoconfigure.AutoConfiguration.imports,将原本spring.factories中的自动配置类移过来了。
2.3SpringBoot2.6.x及2.7.x获取候选自动配置类差异
2.7.x版本新增了@AutoConfiguration标记类的处理
2.4SpringBoot3.x获取候选自动配置类
3.x后移除了spring.factories的处理
2.5redis自动配置差异
2.7.x版本后引入了@Au