RedisTemplate 原生命令操作教程
一、基础配置
<!-- Spring Boot Redis Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- JSON序列化工具(可选,用于复杂对象存储) -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>最新版本</version>
</dependency>
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> template = new RedisTemplate<>();
// 配置连接工厂(默认使用Lettuce,可省略)
return template;
}
}
二、核心操作实现
1. 原生字符串操作
存储字符串(带过期时间)
public void setRawStr(String key, String value, Long expireSeconds) {
redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);
connection.stringCommands().set(keyBytes, valueBytes);
if (expireSeconds != null && expireSeconds > 0) {
connection.keyCommands().expire(keyBytes, expireSeconds);
}
return null;
});
}
使用示例:
setRawStr("message", "Hello Redis!", 60); // 存储60秒后过期
获取字符串
public String getRawStr(String key) {
return redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
byte[] valueBytes = connection.stringCommands().get(keyBytes);
return valueBytes == null ? null : new String(valueBytes, StandardCharsets.UTF_8);
});
}
使用示例:
String msg = getRawStr("message");
System.out.println(msg); // 输出: Hello Redis!
2. 哈希表操作
批量存储键值对(自动JSON序列化)
public void rawHashPutAll(String key, Map<String, Object> hashEntries) {
redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
for (Map.Entry<String, Object> entry : hashEntries.entrySet()) {
byte[] fieldBytes = entry.getKey().getBytes(StandardCharsets.UTF_8);
// 将对象转为JSON字符串存储
byte[] valueBytes = JSONUtil.toJsonStr(entry.getValue()).getBytes(StandardCharsets.UTF_8);
connection.hashCommands().hSet(keyBytes, fieldBytes, valueBytes);
}
return null;
});
}
使用示例:
Map<String, Object> user = new HashMap<>();
user.put("id", "1001");
user.put("name", "李四");
user.put("email", "lisi@example.com");
rawHashPutAll("user:1001", user);
获取哈希字段值
public String getRawHashField(String key, String field) {
return redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
byte[] fieldBytes = field.getBytes(StandardCharsets.UTF_8);
byte[] valueBytes = connection.hashCommands().hGet(keyBytes, fieldBytes);
return valueBytes == null ? null : new String(valueBytes, StandardCharsets.UTF_8);
});
}
使用示例:
String name = getRawHashField("user:1001", "name");
System.out.println(name); // 输出: 李四
3. 列表操作
向列表右侧添加元素
public void rawRightPush(String key, String value) {
redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);
connection.listCommands().rPush(keyBytes, valueBytes);
return null;
});
}
使用示例:
rawRightPush("tasks", "完成项目报告");
从列表左侧弹出元素(补充)
public String rawLeftPop(String key) {
return redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
byte[] valueBytes = connection.listCommands().lPop(keyBytes);
return valueBytes == null ? null : new String(valueBytes, StandardCharsets.UTF_8);
});
}
使用示例:
String task = rawLeftPop("tasks");
System.out.println("处理任务: " + task);
4. 集合操作
添加元素(自动去重)
public void addSetElements(String key, String... values) {
redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
for (String value : values) {
byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);
connection.setCommands().sAdd(keyBytes, valueBytes);
}
return null;
});
}
使用示例:
addSetElements("user:1001:roles", "admin", "editor");
获取元素
public Set<String> getSetElements(String key) {
return redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
Set<byte[]> members = connection.setCommands().sMembers(keyBytes);
Set<String> result = new HashSet<>();
if (members != null) {
for (byte[] member : members) {
result.add(new String(member, StandardCharsets.UTF_8));
}
}
return result;
});
}
判断元素是否存在
public Boolean isSetMember(String key, String value) {
return redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);
return connection.setCommands().sIsMember(keyBytes, valueBytes);
});
}
使用示例:
Boolean isAdmin = isSetMember("user:1001:roles", "admin");
System.out.println("是否为管理员: " + isAdmin);
5. 有序集合操作
添加带分数的元素
public void addZSetElement(String key, String value, double score) {
redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);
connection.zSetCommands().zAdd(keyBytes, score, valueBytes);
return null;
});
}
使用示例:
addZSetElement("product:ranking", "iPhone", 9.8);
按分数范围获取元素
public Set<String> getZSetByScore(String key, double min, double max) {
return redisTemplate.execute((RedisConnection connection) -> {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
Set<byte[]> valueBytesSet = connection.zSetCommands().zRangeByScore(keyBytes, min, max);
Set<String> result = new HashSet<>();
for (byte[] bytes : valueBytesSet) {
result.add(new String(bytes, StandardCharsets.UTF_8));
}
return result;
});
}
使用示例:
Set<String> topProducts = getZSetByScore("product:ranking", 9.0, 10.0);
System.out.println("高分产品: " + topProducts);
三、完整示例:用户积分排行榜
public class UserScoreService {
// 添加用户积分
public void addUserScore(String userId, double score) {
addZSetElement("user:score:ranking", userId, score);
}
// 获取Top 10用户
public Set<String> getTop10Users() {
return getZSetByScore("user:score:ranking", Double.MIN_VALUE, Double.MAX_VALUE)
.stream()
.limit(10)
.collect(Collectors.toSet());
}
}
// 使用示例
UserScoreService service = new UserScoreService();
service.addUserScore("user1001", 95.5);
service.addUserScore("user1002", 88.0);
Set<String> topUsers = service.getTop10Users();
System.out.println("Top 10用户: " + topUsers);