• ef 仓储模式 Redis


    接着写一下 上一章提到的  

    BaseRepositoryRedis.cs


    先说说题外话:由于公司希望用到缓存来提高访问速度。那么我理所当然的想到redis。

    这个无可厚非。可是当时我们的项目已经开发的差不多的了。。。。

    我懒,也不可能到bll或者 dal去增加缓存代码。

    于是我就想到了,既然我们的dal可以继承自BaseRepository.cs 那么一样也可以继承BaseRepositoryRedis.cs

    只需要coder自己来选择是否需要缓存,需要的继承BaseRepositoryRedis,否则继承BaseRepository就好了!!!


    说了这么多,那么放代码,

    先创建一个RedisManager类(随便封装一下)

    public class RedisManager<T> : BaseClass
        {
            RedisClient client = new RedisClient(RedisPath);
    
    
            #region RedisHelper
    
            /// <summary>
            /// 获取
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <returns></returns>
            public virtual T Get<T>(string key)
            {
                var q = client.Get<T>(key);
                return q;
            }
    
            /// <summary>
            /// 设置
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="t"></param>
            /// <param name="expired"></param>
            /// <returns></returns>
            public virtual bool Set<T>(string key,T t,bool expired=true)
            {
                bool q=false;
                if (expired)
                {
                    q = client.Set(key, t,DateTime.Now.AddDays(ExpiredTime));
                }
                else
                {
                    q = client.Set(key, t);
                }
                
                return q;
            }
    
            /// <summary>
            /// 清空缓存
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="t"></param>
            public virtual bool Remove(string key)
            {
                return client.Remove(key);
            }
    
            /// <summary>
            /// 清空所有缓存
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="t"></param>
            public virtual void FlushAll()
            {
                client.FlushAll();
            }
    
            /// <summary>
            /// 获取所有key
            /// </summary>
            public virtual List<string> GetAllKeys()
            {
                var q = client.GetAllKeys();
                return q;
            }
    
            /// <summary>
            /// 获取所有键值对
            /// </summary>
            /// <param name="keys"></param>
            /// <returns></returns>
            public virtual IDictionary<string, T> GetAll(List<string> keys)
            {
                IDictionary<string, T> dict = client.GetAll<T>(keys);
                return dict;
            }
    
            #endregion
    
        }

    然后创建接口

    IDAL

    namespace IDAL
    {
        public interface IBaseRepositoryRedis<T>
        {
            /// <summary>
            /// 添加
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>添加后的数据实体</returns>
            T Add(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 添加
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>添加后的数据实体</returns>
            bool AddOK(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 查询记录数
            /// </summary>
            /// <param name="predicate">条件表达式</param>
            /// <returns>记录数</returns>
            int Count(Expression<Func<T, bool>> predicate, bool hasRedis = true);
    
            /// <summary>
            /// 更新
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>是否成功</returns>
            T Update(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 更新
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>是否成功</returns>
            bool UpdateOK(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 删除
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>是否成功</returns>
            bool Delete(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 是否存在
            /// </summary>
            /// <param name="anyLambda">查询表达式</param>
            /// <returns>布尔值</returns>
            bool Exist(Expression<Func<T, bool>> anyLambda, bool hasRedis = true);
    
            /// <summary>
            /// 查询数据
            /// </summary>
            /// <param name="whereLambda">查询表达式</param>
            /// <returns>实体</returns>
            T Find(Expression<Func<T, bool>> whereLambda, bool hasRedis = true);
    
            /// <summary>
            /// 查找数据列表
            /// </summary>
            /// <typeparam name="S">排序</typeparam>
            /// <param name="whereLamdba">查询表达式</param>
            /// <returns></returns>
            List<T> FindList(Expression<Func<T, bool>> whereLamdba, bool hasRedis = true);
    
            /// <summary>
            /// 查找数据列表
            /// </summary>
            /// <typeparam name="S">排序</typeparam>
            /// <param name="whereLamdba">查询表达式</param>
            /// <param name="isAsc">是否升序</param>
            /// <param name="orderLamdba">排序表达式</param>
            /// <returns></returns>
            List<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true);
    
            /// <summary>
            /// 查找分页数据列表
            /// </summary>
            /// <typeparam name="S">排序</typeparam>
            /// <param name="pageIndex">当前页</param>
            /// <param name="pageSize">每页记录数</param>
            /// <param name="totalRecord">总记录数</param>
            /// <param name="whereLamdba">查询表达式</param>
            /// <param name="isAsc">是否升序</param>
            /// <param name="orderLamdba">排序表达式</param>
            /// <returns></returns>
            List<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true);
    
            List<T> FindListBySQL<T>(string sql, params object[] parameters);
            int ExecuteBySQL(string sql, params object[] parameters);
        }
    }


    IBLL

    namespace IBLL
    {
        public interface IBaseRepositoryRedisBLL<T> where T : class
        {
            /// <summary>
            /// 添加
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>添加后的数据实体</returns>
            T Add(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 添加
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>添加后的数据实体</returns>
            bool AddOK(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 查询记录数
            /// </summary>
            /// <param name="predicate">条件表达式</param>
            /// <returns>记录数</returns>
            int Count(Expression<Func<T, bool>> predicate, bool hasRedis = true);
    
            /// <summary>
            /// 更新
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>是否成功</returns>
            T Update(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 更新
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>是否成功</returns>
            bool UpdateOK(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 删除
            /// </summary>
            /// <param name="entity">数据实体</param>
            /// <returns>是否成功</returns>
            bool Delete(T entity, bool hasRedis = true);
    
            /// <summary>
            /// 是否存在
            /// </summary>
            /// <param name="anyLambda">查询表达式</param>
            /// <returns>布尔值</returns>
            bool Exist(Expression<Func<T, bool>> anyLambda, bool hasRedis = true);
    
            /// <summary>
            /// 查询数据
            /// </summary>
            /// <param name="whereLambda">查询表达式</param>
            /// <returns>实体</returns>
            T Find(Expression<Func<T, bool>> whereLambda, bool hasRedis = true);
    
            /// <summary>
            /// 查找数据列表
            /// </summary>
            /// <typeparam name="S">排序</typeparam>
            /// <param name="whereLamdba">查询表达式</param>
            /// <returns></returns>
            List<T> FindList(Expression<Func<T, bool>> whereLamdba, bool hasRedis = true);
    
            /// <summary>
            /// 查找数据列表
            /// </summary>
            /// <typeparam name="S">排序</typeparam>
            /// <param name="whereLamdba">查询表达式</param>
            /// <param name="isAsc">是否升序</param>
            /// <param name="orderLamdba">排序表达式</param>
            /// <returns></returns>
            List<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true);
    
            /// <summary>
            /// 查找分页数据列表
            /// </summary>
            /// <typeparam name="S">排序</typeparam>
            /// <param name="pageIndex">当前页</param>
            /// <param name="pageSize">每页记录数</param>
            /// <param name="totalRecord">总记录数</param>
            /// <param name="whereLamdba">查询表达式</param>
            /// <param name="isAsc">是否升序</param>
            /// <param name="orderLamdba">排序表达式</param>
            /// <returns></returns>
            List<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true);
    
            List<T> FindListBySQL<T>(string sql, params object[] parameters);
            int ExecuteBySQL(string sql, params object[] parameters);
        }
    }


    DAL

    这里,我们创建 BaseRepositoryRedis

    namespace DAL.Base
    {
        public class BaseRepositoryRedis<T> : BaseClass, IBaseRepositoryRedis<T> where T : class
        {
            public ELDBEntity dbEF = DbContextFactory.GetCurrentContext();
            RedisBLL<T> redis = new RedisBLL<T>();
    
            public virtual T Add(T entity,bool hasRedis=true)
            {
                dbEF.Entry<T>(entity).State = EntityState.Added;
                dbEF.SaveChanges();
                if (hasRedis)
                {
                    var q = SaveRedis();
                }
                return entity;
            }
    
            public virtual bool AddOK(T entity, bool hasRedis = true)
            {
                dbEF.Entry<T>(entity).State = EntityState.Added;
                int count = dbEF.SaveChanges();
                if (hasRedis)
                {
                    var q = SaveRedis();
                }
                return count > 0;
            }
    
            public virtual int Count(Expression<Func<T, bool>> predicate, bool hasRedis = true)
            {
                List<T> q = new List<T>();
    
                if (hasRedis)
                {
                    var s = redis.Get<string>(typeof(T).ToString());
                    if (string.IsNullOrEmpty(s))
                    {
                        q = SaveRedis();
                    }
                    else
                    {
                        q = JsonConvert.DeserializeObject<List<T>>(s);
                    }
                    return q.Count(predicate.Compile());
                }
                return dbEF.Set<T>().AsNoTracking().Count(predicate);
            }
    
            public virtual T Update(T entity, bool hasRedis = true)
            {
                dbEF.Set<T>().Attach(entity);
                dbEF.Entry<T>(entity).State = EntityState.Modified;
                dbEF.SaveChanges();
                if (hasRedis)
                {
                    var q = SaveRedis();
                }
                return entity;
            }
    
            public virtual bool UpdateOK(T entity, bool hasRedis = true)
            {
                dbEF.Set<T>().Attach(entity);
                dbEF.Entry<T>(entity).State = EntityState.Modified;
                int count = dbEF.SaveChanges();
                if (hasRedis)
                {
                    var q = SaveRedis();
                }
                return count>0;
            }
    
            public virtual bool Delete(T entity, bool hasRedis = true)
            {
                dbEF.Set<T>().Attach(entity);
                dbEF.Entry<T>(entity).State = EntityState.Deleted;
                int count = dbEF.SaveChanges(); 
                if (hasRedis)
                {
                    var q = SaveRedis();
                }
                return count > 0;
            }
    
            public virtual bool Exist(Expression<Func<T, bool>> anyLambda, bool hasRedis = true)
            {
                List<T> q = new List<T>();
    
                if (hasRedis)
                {
                    var s = redis.Get<string>(typeof(T).ToString());
                    if (string.IsNullOrEmpty(s))
                    {
                        q = SaveRedis();
                    }
                    else
                    {
                        q = JsonConvert.DeserializeObject<List<T>>(s);
                    }
                    return q.Exists(anyLambda.Compile().ToPredicate());
                }
                return dbEF.Set<T>().AsNoTracking().Any(anyLambda);
            }
    
            public virtual T Find(Expression<Func<T, bool>> whereLambda, bool hasRedis = true)
            {
                List<T> q = new List<T>();
    
                if (hasRedis)
                {
                    var s = redis.Get<string>(typeof(T).ToString());
                    if (string.IsNullOrEmpty(s))
                    {
                        q = SaveRedis();
                    }
                    else
                    {
                        q = JsonConvert.DeserializeObject<List<T>>(s);
                    }
    
                    return q.Find(whereLambda.Compile().ToPredicate());
                }
                T _entity = dbEF.Set<T>().AsNoTracking().FirstOrDefault<T>(whereLambda);
                return _entity;
            }
    
            public virtual List<T> FindList(Expression<Func<T, bool>> whereLamdba, bool hasRedis = true)
            {
                List<T> q = new List<T>();
    
                if (hasRedis)
                {
                    var s = redis.Get<string>(typeof(T).ToString());
                    if (string.IsNullOrEmpty(s))
                    {
                        q = SaveRedis();
                    }
                    else
                    {
                        q = JsonConvert.DeserializeObject<List<T>>(s);
                    }
                }
                else
                {
                    q = dbEF.Set<T>().AsNoTracking().Where<T>(whereLamdba).ToList();
                }
                return q.FindAll(whereLamdba.Compile().ToPredicate());;
            }
    
            public virtual List<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
            {
                List<T> q = new List<T>();
    
                if (hasRedis)
                {
                    var s = redis.Get<string>(typeof(T).ToString());
                    if (string.IsNullOrEmpty(s))
                    {
                        q = SaveRedis();
                    }
                    else
                    {
                        q = JsonConvert.DeserializeObject<List<T>>(s);
                    }
                    q = q.FindAll(whereLamdba.Compile().ToPredicate());
                    
                }
                else
                { 
                    q=dbEF.Set<T>().AsNoTracking().Where<T>(whereLamdba).ToList();
                }
                if (isAsc) q = q.OrderBy<T, S>(orderLamdba.Compile()).ToList();
                else q = q.OrderByDescending<T, S>(orderLamdba.Compile()).ToList();
                return q;
            }
    
            public virtual List<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
            {
                List<T> q = new List<T>();
    
                if (hasRedis)
                {
                    var s = redis.Get<string>(typeof(T).ToString());
                    if (string.IsNullOrEmpty(s))
                    {
                        q = SaveRedis();
                    }
                    else
                    {
                        q = JsonConvert.DeserializeObject<List<T>>(s);
                    }
    
                    q = q.FindAll(whereLamdba.Compile().ToPredicate());
                    
                }
                else
                {
                    q = dbEF.Set<T>().AsNoTracking().Where<T>(whereLamdba).ToList();
                }
                totalRecord = q.Count();
                if (isAsc) q = q.OrderBy<T, S>(orderLamdba.Compile()).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize).ToList();
                else q = q.OrderByDescending<T, S>(orderLamdba.Compile()).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize).ToList();
                return q;
            }
            public virtual PagedList<T> FindPageList1<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
            {
                List<T> q = new List<T>();
                if (hasRedis)
                {
                    var s = redis.Get<string>(typeof(T).ToString());
                    if (string.IsNullOrEmpty(s))
                    {
                        q = SaveRedis();
                    }
                    else
                    {
                        q = JsonConvert.DeserializeObject<List<T>>(s);
                    }
    
                    q = q.FindAll(whereLamdba.Compile().ToPredicate());
                    
                }
                else
                {
                    q = dbEF.Set<T>().AsNoTracking().Where<T>(whereLamdba).ToList();
                }
                totalRecord = q.Count();
                PagedList<T> resultList = null;
                if (isAsc) resultList = q.OrderBy<T, S>(orderLamdba.Compile()).ToPagedList(pageIndex, pageSize);
                else resultList = q.OrderByDescending<T, S>(orderLamdba.Compile()).ToPagedList(pageIndex, pageSize);
                return resultList;
            }
    
    
            public virtual List<T> FindListBySQL<T>(string sql, params object[] parameters)
            {
                var list = dbEF.Database.SqlQuery<T>(sql, parameters).ToList();
                return list;
            }
    
            public virtual int ExecuteBySQL(string sql, params object[] parameters)
            {
                var q = dbEF.Database.ExecuteSqlCommand(sql, parameters);
                return q;
            }
    
            private List<T> SaveRedis()
            {
                List<T> q = dbEF.Set<T>().AsNoTracking().ToList();
                var json = JsonConvert.SerializeObject(q);
                redis.Set<string>(typeof(T).Name, json);
                return q;
            }
        }
    }


    PS:说一下,为何要用json存储? 其实我也很无奈(Redis抓狂 无法保存ef复杂对象),看链接:http://blog.csdn.net/hanjun0612/article/details/54409892


    BLL

    namespace BLL.Base
    {
        public class BaseRepositoryRedisBLL<T> : BaseClass, IBaseRepositoryRedisBLL<T> where T : class
        {
            BaseRepositoryRedis<T> obj = new BaseRepositoryRedis<T>();
            public virtual T Add(T entity, bool hasRedis = true)
            {
                return obj.Add(entity);
            }
    
            public virtual bool AddOK(T entity, bool hasRedis = true)
            {
                return obj.AddOK(entity);
            }
    
            public virtual int Count(System.Linq.Expressions.Expression<Func<T, bool>> predicate, bool hasRedis = true)
            {
                return obj.Count(predicate);
            }
    
            public virtual T Update(T entity, bool hasRedis = true)
            {
                return obj.Update(entity);
            }
    
            public virtual bool UpdateOK(T entity, bool hasRedis = true)
            {
                return obj.UpdateOK(entity);
            }
    
            public virtual bool Delete(T entity, bool hasRedis = true)
            {
                return obj.Delete(entity);
            }
    
            public virtual bool Exist(System.Linq.Expressions.Expression<Func<T, bool>> anyLambda, bool hasRedis = true)
            {
                return obj.Exist(anyLambda);
            }
    
            public virtual T Find(Expression<Func<T, bool>> whereLambda, bool hasRedis = true)
            {
                return obj.Find(whereLambda);
            }
    
            public virtual List<T> FindList(Expression<Func<T, bool>> whereLamdba, bool hasRedis = true)
            {
                var _list = obj.FindList(whereLamdba);
                return _list;
            }
    
            public virtual List<T> FindList<S>(Expression<Func<T, bool>> whereLamdba, bool isAsc, System.Linq.Expressions.Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
            {
                return obj.FindList<S>(whereLamdba, isAsc, orderLamdba);
            }
    
            public virtual List<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
            {
                return obj.FindPageList<S>(pageIndex, pageSize, out totalRecord, whereLamdba, isAsc, orderLamdba);
            }
    
            public virtual PagedList<T> FindPageList1<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<T, bool>> whereLamdba, bool isAsc, Expression<Func<T, S>> orderLamdba, bool hasRedis = true)
            {
                return obj.FindPageList1<S>(pageIndex, pageSize, out totalRecord, whereLamdba, isAsc, orderLamdba);
            }
    
            public virtual List<T> FindListBySQL<T>(string sql, params object[] parameters)
            {
                return obj.FindListBySQL<T>(sql, parameters);
            }
    
            public virtual int ExecuteBySQL(string sql, params object[] parameters)
            {
                return obj.ExecuteBySQL(sql, parameters);
            }
        }
    }



    最后,看一下用法

    DAL
     public class TestDAL : BaseRepositoryRedis<SYS_User>
        {
            //创建自定义方法
            public string HelloWorld(string name)
            {
                return name + " Hello";
            }
    
        }

    BLL
    namespace BLL.Test
    {
        //继承BaseRepositoryBLL,拥有常用方法
        public class TestBLL : BaseRepositoryRedisBLL<SYS_User>
        {
            
        }
    }


  • 相关阅读:
    Jenkins自动化测试环境搭建
    在windows上运行python程序
    DOS命令笔记
    批处理基础语法
    一键清理c盘垃圾文件--bat文件
    Centos7中打包docker离线包
    python之正则表达式使用
    LoadRunner11使用代理录制脚本
    快速查看日志脚本
    实现两种登录方式一键切换的脚本及相关知识点
  • 原文地址:https://www.cnblogs.com/hanjun0612/p/9779838.html
Copyright © 2020-2023  润新知