SpringBoot集成Redis(全流程详解)

前言

通过在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

image-20241114103352729

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");
    }

}
  • 测试结果:

image-20241114105038125

二、自动配置机制版本差异

Spring Boot自2.7版本开始逐步弃用spring.factories文件,并在3.0版本中将其彻底移除。

2.1SpringBoot2.7版本前

image-20241114110648852

在/META-INF/目录下,包含了一系列的自动配置类,这些类可以在满足特定条件时被Spring Boot自动加载和使用。

2.2SpringBoot2.7.x版本

image-20241114110819604

/META-INF/spring目录下新增了org.springframework.boot.autoconfigure.AutoConfiguration.imports,将原本spring.factories中的自动配置类移过来了。

2.3SpringBoot2.6.x及2.7.x获取候选自动配置类差异

2.7.x版本新增了@AutoConfiguration标记类的处理

image-20241114110001934

2.4SpringBoot3.x获取候选自动配置类

3.x后移除了spring.factories的处理

image-20241114111638663

2.5redis自动配置差异

2.7.x版本后引入了@Au

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

懒惰蜗牛

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

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

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

打赏作者

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

抵扣说明:

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

余额充值