你好世界

Redis在spring中的一些常用api

基本类型:
String
  1. 存储数据:
  • stringRedisTemplate.opsForValue().set("key", "value");
  1. 获取数据:
  • String value = stringRedisTemplate.opsForValue().get("key");
  1. 设置数据的过期时间(单位为秒):
  • stringRedisTemplate.expire("key", 60, TimeUnit.SECONDS);
  1. 删除数据:
  • stringRedisTemplate.delete("key");
  1. 检查 key 是否存在:
  • boolean exists = stringRedisTemplate.hasKey("key");
  1. 自增或自减操作:
  • Long incrementedValue = stringRedisTemplate.opsForValue().increment("key", 1);
  • Long decrementedValue = stringRedisTemplate.opsForValue().decrement("key", 1);
Hash
  1. 设置 Hash 类型数据:
  • stringRedisTemplate.opsForHash().put("hashKey", "field", "value");
  1. 获取 Hash 类型数据:
  • String hashValue = (String) stringRedisTemplate.opsForHash().get("hashKey", "field");
 
List :
  • 向 List 中插入值:
stringRedisTemplate.opsForList().rightPush("listKey", "value1");
  • 从 List 中获取值:
String value = stringRedisTemplate.opsForList().index("listKey", 0);
Set :
  • 向 Set 中添加值:
stringRedisTemplate.opsForSet().add("setKey", "value1");
  • 检查值是否存在于 Set 中:
boolean memberExists = stringRedisTemplate.opsForSet().isMember("setKey", "value1");
Sorted Set 类型:
  • 向 Sorted Set 中添加值,并设置分数:
stringRedisTemplate.opsForZSet().add("zsetKey", "value1", 10.0);
  • 获取指定范围内的值:
Set<String> rangeValues = stringRedisTemplate.opsForZSet().range("zsetKey", 0, -1);
  • 根据分数范围获取元素:
Set<String> rangeByScore = stringRedisTemplate.opsForZSet().rangeByScore("sortedSetKey", 0, 100);
特殊类型:
1. HyperLogLog (基数统计)
HyperLogLog 用于进行基数统计,即对集合中不重复元素的个数进行估计。在 Redis 中,可以使用 HyperLogLog 数据结构来实现这一功能。
使用示例:
// 添加元素到 HyperLogLog stringRedisTemplate.opsForHyperLogLog().add("hyperLogLogKey", "element1", "element2"); // 获取 HyperLogLog 的基数估计值 Long cardinality = stringRedisTemplate.opsForHyperLogLog().size("hyperLogLogKey");
2. GeoSpatial (地理空间)
GeoSpatial 数据结构用于处理地理位置信息,如存储经纬度坐标点,并进行附近位置搜索等操作。
使用示例:
// 添加地理位置信息 stringRedisTemplate.opsForGeo().add("geoKey", new Point(13.361389, 38.115556), "Palermo"); // 获取两个地理位置之间的距离 Distance distance = stringRedisTemplate.opsForGeo().distance("geoKey", "Palermo", "Catania");
3. Bitmaps (位图)
Bitmaps 是一种位数组数据结构,用于存储位的状态(0 或 1),常用于处理一些状态标记或位运算操作。
使用示例:
// 设置位图中指定位置的值 stringRedisTemplate.opsForValue().setBit("bitmapKey", 0, true); // 获取位图中指定位置的值 Boolean bitValue = stringRedisTemplate.opsForValue().getBit("bitmapKey", 0);
 
posted @   constantinealicia  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示