哈希hash又称为散列、杂凑等,是将任意长度的输入通过散列算法变换为固定长度的输出,最终输出也就是哈希值。这种转换是一种压缩映射。也就是说,散列值的空间通常要远小于输入控件,不同的输入可能会散列成相同的输出,所以不可能通过散列值来确定唯一的输入值。
哈希表hash table是为了将数据映射到数组中某个位置,通过数组下标访问元素以提高数据的查询速度,这种查询的平均期望时间复杂度为O(1)。
Redis hash 是一个string类型的field和value的映射表,hash特别适合用于存储对象。Redis 中每个 hash 可以存储 232 - 1 键值对(40多亿)。
读取
var list = new List<InsAuthenticationInfo>();Dictionary<string, string> cache;using (var redisClient = RedisManager.GetReadOnlyClient()){cache = redisClient.GetAllEntriesFromHash(CacheKeys.InsAuthenticationMap);}foreach (var item in cache){if (string.IsNullOrWhiteSpace(item.Key) || item.Value == null)continue;try{var info = JsonHelper.GetObject<InsAuthenticationInfo>(item.Value);if (info != null)list.Add(info);}catch (Exception e){Logger.Error(e, $"解析InsAuthenticationInfo失败,JSON:{item.Value}");}}if (ListIsNull(list))return null;return list.OrderBy(x => x.No, noComparer).ToList();
修改
using (var redisClient = RedisManager.GetClient()){string infoStr = redisClient.GetValueFromHash(CacheKeys.InsAuthenticationMap, info.No);if (string.IsNullOrWhiteSpace(infoStr))throw new Exception($"身份信息不存在,No:{info.No}");try{var updateItem = JsonHelper.GetObject<InsAuthenticationInfo>(infoStr);updateItem.Mid = info.Mid;updateItem.SessionId = info.SessionId;updateItem.CanBeUse = info.CanBeUse;updateItem.UpdateTime = DateTime.Now;redisClient.SetEntryInHash(CacheKeys.InsAuthenticationMap, info.No, JsonHelper.GetJson(updateItem));}catch (Exception e){Logger.Error(e, $"解析InsAuthenticationInfo失败,JSON:{infoStr}");}}