Redis 命令及数据类型 -- Hash

摘要

Hash 数据类型

  • Redis Hash 是一种 key → field → value 的数据结构,本质上是

1
2
3
4
5
key -> Map<String, String>
# 说明
key:Redis 的键(只能是 String)
field:Hash 内的字段名(String)
value:字段值(String,二进制安全)
  • Hash 的核心特性

1
2
3
4
5
适合存储对象型数据
支持 字段级别读写
所有操作均为 原子性
内存效率优于「String + JSON」
单个 Hash 理论最大 512 MB
  • 生产环境建议

1
2
3
4
5
一个 Hash = 一个对象
field 数量建议 < 100
单 field value 建议 < 1 KB
大对象拆分为多个 Hash
避免在大 Hash 上使用 HGETALL
  • SpringBoot 的 RedisTemplate<K,V> 中 Hash 数据类型 的操作方法与 Redis 原生命令的对应关系如下:

方法功能 方法redisTemplate.opsForHash().xxx() Redis 原始命令 命令备注 / 推荐替代
删除一个或多个 hash field Long delete(H key, Object... hashKeys) HDEL key field [field ...] 返回删除 field 数量
判断 hash field 是否存在 Boolean hasKey(H key, Object hashKey) HEXISTS key field
获取指定 field 的值 HV get(H key, Object hashKey) HGET key field field 不存在返回 null
批量获取多个 field 的值 List<HV> multiGet(H key, Collection<HK> hashKeys) HMGET key field [field ...] 不存在的 field 返回 null
hash field 整数自增 Long increment(H key, HK hashKey, long delta) HINCRBY key field increment value 必须是整数
hash field 浮点数自增 Double increment(H key, HK hashKey, double delta) HINCRBYFLOAT key field increment Redis ≥ 2.6
随机返回一个 field HK randomKey(H key) HRANDFIELD key Redis ≥ 6.2
随机返回一个 field-value Map.Entry<HK,HV> randomEntry(H key) HRANDFIELD key WITHVALUES Redis ≥ 6.2
随机返回多个 field List<HK> randomKeys(H key, long count) HRANDFIELD key count count < 0 可重复
随机返回多个 field-value Map<HK,HV> randomEntries(H key, long count) HRANDFIELD key count WITHVALUES Redis ≥ 6.2
获取 hash 中所有 field Set<HK> keys(H key) HKEYS key O(N),大 hash 慎用
获取 field 对应 value 长度 Long lengthOfValue(H key, HK hashKey) HSTRLEN key field field 不存在返回 0
获取 hash 中 field 数量 Long size(H key) HLEN key
批量设置 field-value void putAll(H key, Map<HK,HV> m) HMSET key field value [...] 已废弃 Redis 4+ 实际映射为 HSET
设置单个 field-value void put(H key, HK hashKey, HV value) HSET key field value 新增或覆盖
field 不存在时设置 Boolean putIfAbsent(H key, HK hashKey, HV value) HSETNX key field value 原子操作
获取所有 value List<HV> values(H key) HVALS key O(N)
获取所有 field-value Map<HK,HV> entries(H key) HGETALL key 生产环境慎用
游标扫描 hash Cursor<Map.Entry<HK,HV>> scan(H key, ScanOptions options) HSCAN key cursor [MATCH] [COUNT] 推荐替代 HGETALL
为指定 field 设置过期时间 ExpireChanges<HK> expire(H key, Duration timeout, Collection<HK> hashKeys) HEXPIRE key seconds FIELDS n field [...] Redis ≥ 7.0
为指定 field 设置过期时间点 ExpireChanges<HK> expireAt(H key, Instant expireAt, Collection<HK> hashKeys) HEXPIREAT key timestamp FIELDS n field [...] Redis ≥ 7.0
设置 field 过期策略(高级) ExpireChanges<HK> expire(H key, Expiration expiration, ExpirationOptions options, Collection<HK> hashKeys) HEXPIRE / HEXPIREAT Spring 抽象封装
移除指定 field 的过期时间 ExpireChanges<HK> persist(H key, Collection<HK> hashKeys) HPERSIST key FIELDS n field [...] Redis ≥ 7.0