码迷,mamicode.com
首页 > 其他好文 > 详细

redis 储存对象

时间:2020-05-13 00:40:34      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:help   集合   for   omr   red   sts   tin   div   rop   

如果我们储存的对象为数组或集合,我们可以采用转json的方法开存储。

保存

         var objStr = JsonConvert.SerializeObject(postList);//这里的postList为数据库取出的对象集合
                byte[] bytes = Encoding.UTF8.GetBytes(objStr);
                db.StringSet(dbKey, bytes, TimeSpan.FromMinutes(5));

取出

 if (db.KeyExists(dbKey))
            {
                var resStr = db.StringGet(dbKey);
                var resStrEncoding = Encoding.UTF8.GetString(resStr);
                var res = JsonConvert.DeserializeObject<List<Post>>(resStr);
            }

对于没那么复杂的对象我们的hash就更好用了

  public class RedisHelper
    {
        public static HashEntry[] ToHashEnties(object obj)
        {
            PropertyInfo[] properties = obj.GetType().GetProperties();
            return properties.Select(proterty => new HashEntry(proterty.Name, proterty.GetValue(obj).ToString())).ToArray();
        }
        public static T ConvertFromRedis<T>(HashEntry[] hashEntries)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            var obj = Activator.CreateInstance(typeof(T));
            foreach (var property in properties)
            {
                HashEntry entry = hashEntries.FirstOrDefault(g => g.Name.ToString().Equals(property.Name));
                if (entry.Equals(new HashEntry()))
                {
                    continue;
                }
                property.SetValue(obj, Convert.ChangeType(entry.Value.ToString(), property.PropertyType));
            }
            return (T)obj;
        }

    }

 

redis 储存对象

标签:help   集合   for   omr   red   sts   tin   div   rop   

原文地址:https://www.cnblogs.com/hurui1/p/12879812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!