Rob*_*ler 6 hash redis spring-boot
我有一个使用 Redis 进行存储的 Java Spring Boot 应用程序。我已经做了网络搜索了相当数量的,但我不能找到一个容易消化的文字,在细节的什么值使用/选择的后果解释键与参数哈希键在Redis的参数投入(关键,哈希键,对象)语句。我正在使用 Redis 存储来存储特定于特定用户 ID 的短期会话管理对象,并且该用户 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)
Run Code Online (Sandbox Code Playgroud)
这两个参数之间有什么区别,您是否知道解释不同选择的性能和价值冲突后果的文档?此外,鉴于我的存储操作的性质,我是否需要担心 Redis 分片或其他专家级别的细节,或者我现在可以合理地忽略它们吗?该应用程序一旦投入生产,将面临高流量负载。
基本上在你的场景中:
your key is: userid:store:multi_select_choices
your hashkey is: userid
and your options objects serialized into jsonRedisValue
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您不需要使用:
redisTemplate.opsForHash().put(key, hashKey, jsonRedisValue)
Run Code Online (Sandbox Code Playgroud)
相反,你应该使用:
redisTemplate.opsForValue().put(key, jsonRedisValue)
Run Code Online (Sandbox Code Playgroud)
这是一个非常好的例子,可以帮助您理解 opsForHash 有意义的场景:
首先你必须明白,redis中的哈希值是对象的完美表示,因此你不需要序列化对象,而只需以多个键值对的格式存储对象即可,例如对于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")
Run Code Online (Sandbox Code Playgroud)
稍后如果您想更改密码,只需执行以下操作:
redisTemplate.opsForHash().put("userid:1000", "password", "654321")
Run Code Online (Sandbox Code Playgroud)
以及使用 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"
Run Code Online (Sandbox Code Playgroud)
我没有过多探讨它如何实现哈希操作的基本原理,但我认为根据文档,key和hashkey之间的区别非常明显,key就像其他redis键一样,普通字符串,hashkey是为了目的优化多个键值对的存储,所以我猜后面一定有某种哈希算法来保证最佳的内存存储和更快的查询和更新。
这里有详细记录:
https://redis.io/topics/data-types
https://redis.io/topics/data-types-intro
归档时间: |
|
查看次数: |
1410 次 |
最近记录: |