# SpringBoot集成Redis教程

# 1. 环境准备

# 1.1 基础软件版本要求

SpringBoot 3.x 系列要求 JDK 版本≥17(核心依赖限制),请确保你的开发环境满足以下条件:

  • IDE:IntelliJ IDEA 2023+(社区版/旗舰版均可)
  • JDK:17 或更高版本(推荐17 LTS)
  • SpringBoot:3.5.9
  • Redis:8.0.5
  • 依赖管理:Maven 3.9.4 或 Gradle 8.0+(本教程用Maven)

# 1.2 Redis 服务前置配置

确保你的Redis服务(IP:192.168.31.113,端口:6379)已正确配置并启动:

  1. 修改Redis配置文件(redis.conf):
    • 注释 bind 127.0.0.1 或改为 bind 0.0.0.0(允许远程连接)
    • 设置 protected-mode no(关闭保护模式)
    • 设置密码:requirepass admin123456
    • 设置用户名(Redis6+支持):acl setuser hepadmin on >admin123456 allkeys allcommands
  2. 重启Redis服务,验证连接:
    # 连接Redis
    redis-cli -h 192.168.31.113 -p 6379 -u hepadmin -a admin123456
    # 测试是否连通
    ping
    # 正常返回 PONG 则说明服务可用
    
    1
    2
    3
    4
    5

# 2. 创建SpringBoot项目(IDEA)

# 2.1 新建Spring Initializr项目

003

# 2.2 验证项目基础结构

启动类 SpringBootRedisApplication.java 无需修改,默认内容如下:

package cc.hep;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRedisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootRedisApplication.class, args);
	}

}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3. Redis核心配置

# 3.1 配置文件(application.yml)

SpringBoot默认支持yml配置(比properties更简洁),在src/main/resources下编写application.yml,填入Redis连接信息:

# SpringBoot核心配置
spring:
  # Redis配置
  data:
    redis:
      # 连接地址
      host: 192.168.31.113
      # 端口
      port: 6379
      # 用户名(Redis6+必填)
      username: hepadmin
      # 密码
      password: hep1029384756
      # 选择Redis数据库(0-15,默认0)
      database: 0
      # 连接超时时间(毫秒)
      timeout: 20000
      # Lettuce连接池配置(SpringBoot3默认用Lettuce,替代Jedis)
      lettuce:
        pool:
          # 最大活跃连接数
          max-active: 8
          # 最大空闲连接数
          max-idle: 8
          # 最小空闲连接数
          min-idle: 0
          # 最大等待时间(毫秒,-1表示无限制)
          max-wait: -1ms
# 日志配置(便于调试Redis操作)
logging:
  level:
    org.springframework.data.redis: DEBUG
    cc.hep: INFO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# 3.2 配置参数说明

参数 作用
spring.data.redis.host Redis服务IP地址
spring.data.redis.port Redis服务端口(默认6379)
spring.data.redis.username Redis6+新增的用户名(非必填,若未设置可省略)
spring.data.redis.password Redis访问密码
spring.data.redis.database Redis数据库索引(不同索引对应不同的独立数据空间,避免数据冲突)
spring.data.redis.lettuce.pool Lettuce连接池配置(复用连接,提升性能,企业级必配)

# 4. 自定义RedisTemplate(解决序列化问题)

SpringBoot默认提供的RedisTemplate使用JDK序列化,存储的数据是乱码(如\xAC\xED\x00\x05t\x00\x03key),企业级开发需自定义序列化规则(用JSON序列化)。

# 4.1 编写Redis配置类

在config包下创建RedisConfig.java:

package cc.hep.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Redis 配置类:解决 LocalDateTime 序列化问题
 */
@Configuration
public class RedisConfig {

    // 定义时间格式化规则
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 1. 配置 Jackson2JsonRedisSerializer,处理 Java 8 时间类型
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();

        // 注册 JavaTimeModule,处理 LocalDateTime
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 序列化 LocalDateTime
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER));
        // 反序列化 LocalDateTime
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DATE_TIME_FORMATTER));

        objectMapper.registerModule(javaTimeModule);
        // 允许序列化空值
        objectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 关闭类型检查(兼容序列化)
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 2. 设置 RedisTemplate 的序列化规则
        // key 用 String 序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // value 用 Jackson 序列化(支持 LocalDateTime)
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

# 4.2 配置类核心说明

  1. 序列化器选择:
    • StringRedisSerializer:序列化Key(保证Key是可读的字符串)
    • Jackson2JsonRedisSerializer:序列化Value(将对象转为JSON字符串,可读性高,跨语言兼容)
  2. 类型信息开启:activateDefaultTyping 保证反序列化时能正确识别对象类型(比如User对象不会被反序列化为Map)。

# 5. 封装Redis通用操作工具类(企业级)

企业级开发中,不会直接使用RedisTemplate编写重复代码,而是封装通用工具类RedisUtil,覆盖Redis常用数据类型(String、Hash、List、Set、ZSet)的增删改查。

# 5.1 编写RedisUtil工具类

在utils包下创建RedisUtil.java:

package cc.hep.utils;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis通用操作工具类(企业级封装)
 */
@Component
public class RedisUtil {

    // 注入自定义的RedisTemplate
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // ====================== String类型操作 ======================
    /**
     * 设置String类型值
     * @param key 键
     * @param value 值
     */
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置String类型值(带过期时间)
     * @param key 键
     * @param value 值
     * @param timeout 过期时间
     * @param unit 时间单位
     */
    public void set(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    /**
     * 获取String类型值
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除指定key
     * @param key 键
     * @return 是否删除成功
     */
    public Boolean delete(String key) {
        return key == null ? false : redisTemplate.delete(key);
    }

    /**
     * 批量删除key
     * @param keys 键集合
     * @return 删除的数量
     */
    public Long delete(Collection<String> keys) {
        return keys == null ? 0 : redisTemplate.delete(keys);
    }

    /**
     * 设置key的过期时间
     * @param key 键
     * @param timeout 过期时间
     * @param unit 时间单位
     * @return 是否设置成功
     */
    public Boolean expire(String key, long timeout, TimeUnit unit) {
        return key == null ? false : redisTemplate.expire(key, timeout, unit);
    }

    // ====================== Hash类型操作 ======================
    /**
     * 向Hash中添加字段
     * @param key 键
     * @param hashKey 字段名
     * @param value 字段值
     */
    public void hPut(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    /**
     * 批量向Hash中添加字段
     * @param key 键
     * @param map 字段-值映射
     */
    public void hPutAll(String key, Map<String, Object> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    /**
     * 获取Hash中指定字段的值
     * @param key 键
     * @param hashKey 字段名
     * @return 字段值
     */
    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    /**
     * 获取Hash中所有字段和值
     * @param key 键
     * @return 所有字段-值映射
     */
    public Map<Object, Object> hGetAll(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 删除Hash中指定字段
     * @param key 键
     * @param hashKeys 字段名数组
     * @return 删除的数量
     */
    public Long hDelete(String key, Object... hashKeys) {
        return redisTemplate.opsForHash().delete(key, hashKeys);
    }

    // ====================== List类型操作 ======================
    /**
     * 向List左侧添加元素
     * @param key 键
     * @param value 值
     * @return List长度
     */
    public Long lLeftPush(String key, Object value) {
        return redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     * 向List右侧添加元素
     * @param key 键
     * @param value 值
     * @return List长度
     */
    public Long lRightPush(String key, Object value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    /**
     * 获取List指定索引的元素
     * @param key 键
     * @param index 索引(0开始,负数表示从末尾数)
     * @return 元素
     */
    public Object lIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    /**
     * 获取List指定范围的元素
     * @param key 键
     * @param start 起始索引
     * @param end 结束索引(-1表示最后一个)
     * @return 元素列表
     */
    public List<Object> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    // ====================== Set类型操作 ======================
    /**
     * 向Set中添加元素
     * @param key 键
     * @param values 值数组
     * @return 添加的数量
     */
    public Long sAdd(String key, Object... values) {
        return redisTemplate.opsForSet().add(key, values);
    }

    /**
     * 获取Set中所有元素
     * @param key 键
     * @return 元素集合
     */
    public Set<Object> sMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 判断Set中是否包含指定元素
     * @param key 键
     * @param value 值
     * @return 是否包含
     */
    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    // ====================== ZSet类型操作 ======================
    /**
     * 向ZSet中添加元素(带分数)
     * @param key 键
     * @param value 值
     * @param score 分数
     * @return 是否添加成功
     */
    public Boolean zAdd(String key, Object value, double score) {
        return redisTemplate.opsForZSet().add(key, value, score);
    }

    /**
     * 获取ZSet指定分数范围的元素(升序)
     * @param key 键
     * @param min 最小分数
     * @param max 最大分数
     * @return 元素集合
     */
    public Set<Object> zRangeByScore(String key, double min, double max) {
        return redisTemplate.opsForZSet().rangeByScore(key, min, max);
    }

    /**
     * 获取元素在ZSet中的排名(升序,从0开始)
     * @param key 键
     * @param value 值
     * @return 排名
     */
    public Long zRank(String key, Object value) {
        return redisTemplate.opsForZSet().rank(key, value);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236

# 5.2 工具类核心说明

  1. 注解说明:@Component 让Spring扫描并托管该类,@Resource 注入自定义的RedisTemplate;
  2. 功能覆盖:封装了Redis最常用的5种数据类型操作,满足90%以上的企业级场景;
  3. 异常处理:工具类未额外捕获异常(企业级建议在业务层统一处理),保持代码简洁。

# 6. 业务层与控制层实现(测试示例)

# 6.1 创建测试实体类

在entity包下创建User.java(模拟业务对象):

package cc.hep.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 用户实体类(需实现Serializable,兼容JDK序列化兜底)
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
    private Long id;         // 用户ID
    private String username; // 用户名
    private String phone;    // 手机号
    private LocalDateTime createTime; // 创建时间
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 6.2 编写业务层

# 6.2.1 Service接口

在service包下创建UserService.java:

package cc.hep.service;

import cc.hep.entity.User;

import java.util.List;

/**
 * 用户业务接口
 */
public interface UserService {
    /**
     * 保存用户到Redis
     * @param user 用户对象
     * @param expireMinutes 过期时间(分钟)
     */
    void saveUser(User user, long expireMinutes);

    /**
     * 根据ID查询用户
     * @param userId 用户ID
     * @return 用户对象
     */
    User getUserById(Long userId);

    /**
     * 批量保存用户到Redis的List
     * @param userList 用户列表
     */
    void saveUserList(List<User> userList);

    /**
     * 获取Redis中的用户列表
     * @return 用户列表
     */
    List<Object> getUserList();

    /**
     * 删除指定ID的用户
     * @param userId 用户ID
     * @return 是否删除成功
     */
    Boolean deleteUser(Long userId);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

# 6.2.2 Service实现类

在service包下创建impl子包,编写UserServiceImpl.java:

package cc.hep.service.impl;

import cc.hep.entity.User;
import cc.hep.service.UserService;
import cc.hep.utils.RedisUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户业务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    // Redis Key前缀(企业级规范:避免Key冲突)
    private static final String USER_KEY_PREFIX = "user:info:";
    private static final String USER_LIST_KEY = "user:list";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void saveUser(User user, long expireMinutes) {
        // 拼接Key:user:info:1
        String key = USER_KEY_PREFIX + user.getId();
        // 保存用户,设置过期时间
        redisUtil.set(key, user, expireMinutes, TimeUnit.MINUTES);
    }

    @Override
    public User getUserById(Long userId) {
        String key = USER_KEY_PREFIX + userId;
        // 获取并强转为User对象
        return (User) redisUtil.get(key);
    }

    @Override
    public void saveUserList(List<User> userList) {
        // 清空原有List(避免数据重复)
        redisUtil.delete(USER_LIST_KEY);
        // 批量添加到List右侧
        for (User user : userList) {
            redisUtil.lRightPush(USER_LIST_KEY, user);
        }
    }

    @Override
    public List<Object> getUserList() {
        // 获取List所有元素(0到-1表示全部)
        return redisUtil.lRange(USER_LIST_KEY, 0, -1);
    }

    @Override
    public Boolean deleteUser(Long userId) {
        String key = USER_KEY_PREFIX + userId;
        return redisUtil.delete(key);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

# 6.3 编写控制层

在controller包下创建UserController.java:

package cc.hep.controller;

import cc.hep.entity.User;
import cc.hep.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户接口控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 保存单个用户
     * 请求示例:POST /user/save?expireMinutes=30
     * Body:{"id":1,"username":"hepadmin","phone":"13800138000","createTime":"2026-01-22T10:00:00"}
     */
    @PostMapping("/save")
    public String saveUser(@RequestBody User user, @RequestParam long expireMinutes) {
        user.setCreateTime(LocalDateTime.now()); // 自动填充创建时间
        userService.saveUser(user, expireMinutes);
        return "用户保存成功:" + user.getId();
    }

    /**
     * 根据ID查询用户
     * 请求示例:GET /user/1
     */
    @GetMapping("/{userId}")
    public User getUser(@PathVariable Long userId) {
        return userService.getUserById(userId);
    }

    /**
     * 批量保存用户列表
     * 请求示例:POST /user/saveList
     */
    @PostMapping("/saveList")
    public String saveUserList() {
        // 模拟用户列表
        List<User> userList = new ArrayList<>();
        userList.add(new User(12L, "zhangsan", "13900139000", LocalDateTime.now()));
        userList.add(new User(13L, "lisi", "13700137000", LocalDateTime.now()));
        userService.saveUserList(userList);
        return "用户列表保存成功,共" + userList.size() + "条";
    }

    /**
     * 获取用户列表
     * 请求示例:GET /user/list
     */
    @GetMapping("/list")
    public List<Object> getUserList() {
        return userService.getUserList();
    }

    /**
     * 删除用户
     * 请求示例:DELETE /user/1
     */
    @DeleteMapping("/{userId}")
    public String deleteUser(@PathVariable Long userId) {
        Boolean result = userService.deleteUser(userId);
        return result ? "用户删除成功:" + userId : "用户删除失败:" + userId;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

# 7. 测试验证

# 7.1 启动项目

运行SpringBootRedisApplication.java的main方法,控制台输出如下内容表示启动成功:

2026-01-22 10:00:00.000  INFO 12345 --- [           main] c.h.s.SpringBootRedisApplication         : Started SpringBootRedisApplication in 2.5 seconds (process running for 3.0)
1

# 7.2 接口测试(Postman)

请求方式 请求地址 参数/Body 预期结果
POST /user/save?expireMinutes=30 Body:{"id":1,"username":"hepadmin","phone":"13800138000"} 返回“用户保存成功:1”
GET /user/1 无 返回User对象的JSON数据
POST /user/saveList 无 返回“用户列表保存成功,共2条”
GET /user/list 无 返回包含2个User对象的列表
DELETE /user/1 无 返回“用户删除成功:1”

# 7.3 验证Redis数据

通过redis-cli连接Redis,验证数据是否正确:

# 查看String类型用户数据
redis-cli -h 192.168.31.113 -p 6379 -u hepadmin -a admin123456
get "user:info:1"
# 输出(JSON格式,可读):
# {"@class":"cc.hep.entity.User","id":1,"username":"hepadmin","phone":"13800138000","createTime":["java.time.LocalDateTime",["2026-01-22T10:00:00"]]}

# 查看List类型用户列表
lrange "user:list" 0 -1
# 输出包含2个User对象的JSON数据
1
2
3
4
5
6
7
8
9

# 8. 企业级优化建议

# 8.1 连接池优化

根据业务量调整Lettuce连接池参数(在application.yml中):

spring:
  data:
    redis:
      lettuce:
        pool:
          max-active: 20  # 最大活跃连接(根据QPS调整)
          max-idle: 10    # 最大空闲连接
          min-idle: 5     # 最小空闲连接(避免频繁创建连接)
          max-wait: 5000ms # 最大等待时间(超时抛异常)
1
2
3
4
5
6
7
8
9

# 8.2 序列化优化

自定义Jackson序列化配置,解决日期格式化问题:

// 在RedisConfig的objectMapper配置中添加
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
objectMapper.registerModule(new JavaTimeModule()); // 支持LocalDateTime序列化
1
2
3

# 8.3 缓存异常处理

在Service层添加异常捕获,避免Redis宕机导致业务异常:

@Override
public User getUserById(Long userId) {
    try {
        String key = USER_KEY_PREFIX + userId;
        return (User) redisUtil.get(key);
    } catch (Exception e) {
        // 记录日志
        log.error("查询Redis用户失败,userId:{}", userId, e);
        // 降级处理(比如查数据库)
        return null;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

# 8.4 缓存策略优化

  • 缓存穿透:对空值进行缓存(设置短过期时间);
  • 缓存击穿:热点Key设置永不过期,或使用分布式锁;
  • 缓存雪崩:Key的过期时间添加随机值(避免同时过期)。

# 总结

# 关键点回顾

  1. 核心配置:SpringBoot 3.5.9集成Redis需配置application.yml的连接信息,重点关注用户名/密码和连接池;
  2. 序列化:必须自定义RedisTemplate,使用JSON序列化替代默认的JDK序列化,保证数据可读;
  3. 企业级封装:通过RedisUtil封装通用操作,Service层规范Key命名(加前缀),控制层提供REST接口测试;
  4. 优化要点:连接池调优、异常处理、缓存策略是企业级项目的核心要求,需结合业务场景调整。

本教程的项目结构和代码完全遵循企业级规范,可直接复制到IDEA中运行,适配你的Redis服务信息(IP:192.168.31.113,端口:6379,用户:hepadmin,密码:admin123456)。

最近更新: 2026/2/3
 |  Copyright © -Present Kelsen All Rights Reserved. | Author KelsenJing