Redis缓存如何用ResourceKey等字段构建复合键快速查询ResourceValue
Redis Hash 结构适配方案
存储规则设计
采用「固定大Key + 复合字段」的Hash结构实现:
- 大Key统一设置为
resource:i18n:map,便于后续统一管理、过期设置或全量查询 - Hash的Field为三个维度拼接的复合键,拼接规则为
{ResourceKey}:{Language}:{ClientId},用冒号做分隔符避免字段内容冲突 - Hash的Value直接存储对应
ResourceValue字符串,无需额外序列化
写入逻辑替换(C# 示例)
直接遍历资源列表批量写入Hash,替换原有的全量JSON序列化逻辑:
var db = _redis.GetDatabase(); const string redisKey = "resource:i18n:map"; // 避免重复写入可先判断Key是否存在,也可根据业务需求选择覆盖写入 if (!await db.KeyExistsAsync(redisKey)) { var hashEntries = resItem.Select(x => new HashEntry( $"{x.ResourceKey}:{x.Language}:{x.ClientId}", x.ResourceValue )).ToArray(); await db.HashSetAsync(redisKey, hashEntries); return Ok("Resources Added Successfully."); }
查询逻辑替换
查询时直接拼接复合键取对应值,无需全量反序列化,时间复杂度为O(1):
var db = _redis.GetDatabase(); const string redisKey = "resource:i18n:map"; // 传入要查询的三个参数 string targetField = $"{targetResourceKey}:{iLanguageId}:{iClientId}"; string resourceValue = await db.HashGetAsync(redisKey, targetField); // 直接判断是否存在返回即可,不需要额外过滤逻辑
额外适配场景说明
如果后续有批量按ClientId、Language维度查询所有资源的需求,可以新增对应的二级Hash结构,比如大Key为res:client:{clientId}:lang:{langId},存储对应维度下的所有键值对即可。
内容的提问来源于stack exchange,提问作者DonMax
相关产品推荐
相关产品推荐

