Spring Boot RedisTemplate
约 505 字大约 2 分钟
布欧-Lewyon
2026-05-15
依赖与配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>spring:
data:
redis:
host: localhost
port: 6379
password: ${REDIS_PASSWORD:}
timeout: 2000ms
lettuce:
pool:
max-active: 200
max-idle: 50
min-idle: 10RedisTemplate vs StringRedisTemplate
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// JSON 序列化
Jackson2JsonRedisSerializer<Object> jsonSerializer =
new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LazyValidatorFactory.getDefaultPolymorphicTypeValidator(),
ObjectMapper.DefaultTyping.NON_FINAL);
jsonSerializer.setObjectMapper(om);
// Key 用 String 序列化
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
// Value 用 JSON
template.setValueSerializer(jsonSerializer);
template.setHashValueSerializer(jsonSerializer);
template.afterPropertiesSet();
return template;
}
}@Service
public class RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate; // Key 和 Value 都是 String
@Autowired
private RedisTemplate<String, Object> redisTemplate; // Value 是 JSON
// String
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
// Hash
public void hset(String key, String field, Object value) {
redisTemplate.opsForHash().put(key, field, value);
}
public Object hget(String key, String field) {
return redisTemplate.opsForHash().get(key, field);
}
}操作各数据类型
@Service
public class DataTypeService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// String
public void stringOps() {
ValueOperations<String, Object> ops = redisTemplate.opsForValue();
ops.set("key", "value");
ops.set("counter", 1);
ops.increment("counter"); // 2
ops.set("cache", "data", 60, TimeUnit.SECONDS); // 过期
}
// List
public void listOps() {
ListOperations<String, Object> ops = redisTemplate.opsForList();
ops.leftPush("queue", "task1");
ops.rightPushAll("queue", "task2", "task3");
Object task = ops.rightPop("queue");
List<Object> all = ops.range("queue", 0, -1);
}
// Set
public void setOps() {
SetOperations<String, Object> ops = redisTemplate.opsForSet();
ops.add("tags:1", "redis", "java");
ops.add("tags:2", "redis", "python");
Set<Object> intersect = ops.intersect("tags:1", "tags:2");
}
// ZSet
public void zSetOps() {
ZSetOperations<String, Object> ops = redisTemplate.opsForZSet();
ops.add("ranking", "Alice", 100);
ops.add("ranking", "Bob", 85);
Set<Object> top = ops.reverseRange("ranking", 0, 9);
Double score = ops.score("ranking", "Alice");
}
// Hash
public void hashOps() {
HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
ops.put("user:100", "name", "Alice");
ops.put("user:100", "age", 25);
String name = (String) ops.get("user:100", "name");
Map<String, Object> all = ops.entries("user:100");
}
}过期与删除
// 设置过期
redisTemplate.expire("key", 60, TimeUnit.SECONDS);
// 获取 TTL
Long ttl = redisTemplate.getExpire("key");
// 删除
redisTemplate.delete("key");
redisTemplate.delete(List.of("key1", "key2"));
// 判断存在
Boolean exists = redisTemplate.hasKey("key");小结
StringRedisTemplate:Key/Value 都是 String(JSON 字符串自行解析)。RedisTemplate<String, Object>:Value 序列化为 JSON(需配置 Jackson)。opsForValue/List/Set/ZSet/Hash分别操作不同数据类型。- 序列化配置:Key 用
StringRedisSerializer,Value 用Jackson2JsonRedisSerializer。 - Spring Boot + RedisTemplate 是 Java 项目集成 Redis 的标准方式。
上一节:Jedis 与 Lettuce 下一节:Redisson 分布式组件
