spring-boot - Redis put() 语句中使用的键和散列键参数有什么区别?

标签 spring-boot hash redis

我有一个使用 Redis 进行存储的 Java Spring Boot 应用程序。我已经进行了大量的网络搜索,但找不到易于理解的文本来详细解释 key 参数与 使用/选择什么值的后果Redis put(key, hash key, object) 语句中的 hash key 参数。我正在使用 Redis 存储来存储特定于特定用户 ID 的短期 session 管理对象,并且保证该用户 ID 是唯一的。对象值是特定类对象的 JSON 编码字符串:

// String format template for storing objects of this class.
public static final String STORE_MULTI_SELECT_CHOICES = "%s:store:multi_select_choices"

// Store it in Redis for access during the next interaction with the user.
// The key is the hash key prefix for the MultiSelectChoices class, followed
//   by the user ID.
String key = String.format(MultiSelectChoices.STORE_MULTI_SELECT_CHOICES, userId)

// The hash key is just the user ID for now.
String hashKey = userId

// Serialize the multi-select session management object to a JSON string.
Gson gson = new Gson();
String jsonRedisValue = gson.toJson(multiSelect);
redisTemplate.opsForHash().put(key, hashKey, jsonRedisValue)

这两个参数之间有什么区别?您是否知道有一篇文档解释了不同选择的性能和值(value)冲突后果?此外,鉴于我的存储操作的性质,我是否需要担心 Redis 分片或其他专家级别的细节,或者我现在可以合理地忽略它们吗?该应用程序一旦投入生产,将面临高流量负载。

最佳答案

基本上在您的场景中:

your key is: userid:store:multi_select_choices
your hashkey is: userid
and your options objects serialized into jsonRedisValue

在这种情况下,您不需要使用:

redisTemplate.opsForHash().put(key, hashKey, jsonRedisValue)

你应该使用:

redisTemplate.opsForValue().put(key, jsonRedisValue)

这是一个很好的例子,可以帮助您理解 opsForHash 有意义的场景:

首先你要明白redis中的hash是对象的完美表示,所以你不需要序列化对象,而是将对象以多个键值对的形式存储,比如一个userid=1000,该对象具有属性:用户名/密码/年龄,您可以像这样简单地将其存储在 redis 上:

redisTemplate.opsForHash().put("userid:1000", "username", "Liu Yue")
redisTemplate.opsForHash().put("userid:1000", "password", "123456")
redisTemplate.opsForHash().put("userid:1000", "age", "32")

稍后如果您想更改密码,只需执行以下操作:

redisTemplate.opsForHash().put("userid:1000", "password", "654321")

以及使用redis-cli的相应cmd:

HMSET userid:1000 username 'Liu Yue' password '123456' age 32
HGETALL userid:1000
1) "username"
2) "Liu Yue"
3) "password"
4) "123456"
5) "age"
6) "32"
HSET userid:1000 password '654321'
HGETALL userid:1000
1) "username"
2) "Liu Yue"
3) "password"
4) "654321"
5) "age"
6) "32"

我没有过多探讨它如何实现哈希操作的基础,但我认为根据文档,key 和 hashkey 之间的区别非常明显,key 就像其他 redis 键一样,普通字符串,hashkey 是为了优化多个键值对的存储,所以我猜想后面一定有某种哈希算法来保证最佳的内存存储和更快的查询和更新。

这里有详细的记录:

https://redis.io/topics/data-types

https://redis.io/topics/data-types-intro

关于spring-boot - Redis put() 语句中使用的键和散列键参数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46062283/

相关文章:

database - 分布式 LSH(局部敏感哈希)

perl - Storable.pm - 保存到未截断的文件时损坏

python - python中的Redis,如何关闭连接?

redis - 在 Redis 中获取当前时间

java - 无法在 Spring Boot 多模块应用程序中的 JUnit 4 测试中 Autowiring 服务

Spring Boot、Elasticsearch 6.2.4、Gradle 依赖问题

spring-boot - 在 Thymeleaf 生成的 HTML 文档中包含 <image>

java - 无法在 Spring Boot 中为每个测试方法初始化数据库

哈希linkedHashSet的java意义

java - 我如何在 spock 测试中使用 redisService 我需要清理 redis 数据库以进行设置和清理