必须先确保redis服务可连、依赖已引入、序列化配置合理,否则存进去的数据乱码或读不出来;spring boot 3.x默认用lettuce客户端,需配json序列化器避免反序列化失败,stringredistemplate适用于纯字符串操作,redistemplate配合genericjackson2jsonredisserializer支持java对象缓存。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

要在Spring Boot项目中用Spring Data Redis写Redis缓存代码,必须先确保Redis服务可连、依赖已引入、序列化配置合理,否则存进去的数据乱码或读不出来。
引入依赖并确认客户端类型
在pom.xml中添加Spring Boot官方推荐的starter:
Spring Boot 3.x默认使用Lettuce(非阻塞、线程安全),【无需额外引入Jedis或commons-pool2】;若用Spring Boot 2.7.x,也无需手动排除Jedis,框架自动选用Lettuce。
配置application.yml连接参数
在application.yml中填写基础连接信息:
spring:
redis:
host: localhost
port: 6379
password: ""
database: 0
timeout: 2000ms
lettuce:
pool:
max-active: 20
max-idle: 10
min-idle: 2
注意:password为空字符串时不能省略引号,否则YAML解析失败;database值必须是0~15之间的整数。
选择模板类:StringRedisTemplate vs RedisTemplate
方法一:纯字符串操作(如短信验证码、计数器)→ 直接注入StringRedisTemplate
@Autowired
private StringRedisTemplate stringRedisTemplate;
这一步操作起来很简单,直接调用set("code:138****1234", "654321", Duration.ofMinutes(5))就行,不用管序列化问题。
方法二:存储Java对象(如User、Order)→ 必须自定义RedisTemplate并配置JSON序列化
Redis 缓存和数据结构管理技能。通过自然语言操作 Redis,支持 String、Hash、List、Set、ZSet、Stream 等数据结构操作。当用户提到 Redis、缓存、消息队列、会话存储时使用此技能。
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate
RedisTemplate
template.setConnectionFactory(factory);
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer();
template.setValueSerializer(jsonSerializer);
template.setHashValueSerializer(jsonSerializer);
return template;
}
}
【不配JSON序列化器会导致value存成乱码字节数组,取出来是null或反序列化失败】
五种数据结构的操作方式
第一步:获取对应Operations实例
ValueOperations
HashOperations
ListOperations
SetOperations
ZSetOperations
第二步:执行典型操作
valueOps.set("user:1001", "张三", Duration.ofHours(1));
hashOps.put("user:1001:profile", "age", 28);
listOps.leftPush("task:queue", new Task("send-email"));
setOps.add("tag:java", "spring", "redis", "boot");
zSetOps.add("leaderboard", "alice", 95.5);
第三步:验证是否生效(可选)
System.out.println(valueOps.get("user:1001")); // 输出:张三
System.out.println(hashOps.entries("user:1001:profile")); // 输出:{age=28}
开启@Cacheable注解式缓存
@EnableCaching加在主启动类或配置类上;然后在Service方法上加:
@Cacheable(value = "users", key = "#id")
public User findById(Long id) {
return userMapper.selectById(id);
}
此时需保证RedisTemplate已配置为支持泛型序列化的版本,否则缓存命中时反序列化会报错ClassCastException。










