Redis 哈希(Hash)

哈希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}");
                }
            }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值