当前位置: 首页 > news >正文

JAVA存储原生json字符串到redis,去除@class,实现原生命令操作教程

RedisTemplate 原生命令操作教程

本文介绍了使用RedisTemplate进行原生命令操作的方法,包括基础配置和核心功能实现。主要内容:1-  基础配置需引入spring-boot-starter-data-redis依赖并配置RedisTemplate;2- 详细演示了五种数据结构的操作:字符串(带过期时间)、哈希表(支持JSON序列化)、列表(左右端操作)、集合(去重特性)、有序集合(带分数排序);3-  提供了用户积分排行榜的完整示例。这些方法通过RedisConnection直接操作字节数组,性能优于高级封装,适合需要精细控制Redis的场景。

一、基础配置

<!-- 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 {@Beanpublic 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);

http://www.dtcms.com/a/305132.html

相关文章:

  • 从传统到智能:Midscene.js 如何用 AI 颠覆自动化测试!
  • 【Lua】题目小练4
  • 深入解析RocksDB的MVCC和LSM Tree level
  • 基于springboot/java/VUE的旅游管理系统/旅游网站的设计与实现
  • USB Type-C PD协议一文通
  • mangoDB面试题及详细答案 117道(026-050)
  • CVE-2021-1675
  • 【C语言进阶】题目练习
  • docker部署zingerbee/netop 轻量级网络流量监控工具
  • 河南萌新联赛2025第(二)场:河南农业大学(补题)
  • 高端医疗超声AFE模拟前端应用
  • 机器学习之线性回归——小白教学
  • 关于为什么写分配法搭配写回法?非写分配法搭配全写法?
  • python基础:request请求查询参数的基本使用、携带请求参数的两种方法、 json串和python中数据类型转化、 post模拟登录
  • 全方位Python学习方法论:从入门到精通的系统指南
  • GB/T 4706.1-2024 家用和类似用途电器的安全 第1部分:通用要求 与2005版差异(21)
  • 【Spring】日志级别的分类和使用
  • 计算机视觉-局部图像描述子
  • 代理IP轮换机制:突破反爬虫的关键策略
  • AI驱动的知识管理新时代:释放组织潜力的关键武器
  • win10 环境删除文件提示文件被使用无法删除怎么办?
  • MPLS 专线网络
  • 字符集学习
  • 实现多路标注截图
  • GESP2025年6月认证C++七级( 第三部分编程题(1)线图)
  • Spring Boot中的this::语法糖详解
  • Spring与数学的完美碰撞
  • 偏二甲肼气体浓度报警控制系统
  • 自适应双门限的能量检测算法
  • Python算法实战:从排序到B+树全解析