天天看點

Redis學習筆記~是時候為Redis實作一個倉儲了,RedisRepository來了

回到目錄

之前寫了不少關于倉儲的文章,是以,自己習慣把自己叫倉儲大叔,上次寫的XMLRepository得到了大家的好評,也有不少朋友給我發email,進行一些知識的探讨,今天主要來實作一個RedisRepository,它始終是內建IRepository接口的,我這裡的Redis倉儲主要服務為複雜類型的業務,對于隻存string這種需求,不需要使用它。

對于Redis倉儲和說,它與XML倉儲有些不同,由于XML檔案一般存儲在WWW伺服器,是以沒有網絡通訊問題,而redis一般部署在第三台伺服器上,我們一般稱為NoSQL伺服器,它與WWW通訊是通過socket協定完成的,正是如些,我們在進行倉儲設計時,應該考慮到如何去釋放它的資源,因為這種資源是非托管的,是以需要人為幹預一下,.net提供了using關鍵字來做這事,而每個動作寫using這顯然是不友好的,是以,我這個redis倉儲是在析構方法裡完成對資源的銷毀的,請看源代碼:

首先是redis基類,它是實作統一操作的前提

  /// <summary>
    /// Redis實體基類,所有redis實體類都應該內建它
    /// </summary>
    public abstract class RedisEntity
    {
        public RedisEntity()
        {
            RootID = Guid.NewGuid().ToString();
        }
        /// <summary>
        /// Redis實體主鍵,方法查詢,删除,更新等操作
        /// </summary>
        public virtual string RootID { get; set; }
    }      

下面才是RedisRepository倉儲的代碼

/// <summary>
    /// Redis倉儲實作
    /// </summary>
    public class RedisRepository<TEntity> :
        IDisposable,
        IRepository<TEntity>
        where TEntity : RedisEntity
    {
        IRedisClient redisDB;
        IRedisTypedClient<TEntity> redisTypedClient;
        IRedisList<TEntity> table;
        public RedisRepository()
        {
            redisDB = RedisManager.GetClient();
            redisTypedClient = redisDB.GetTypedClient<TEntity>();
            table = redisTypedClient.Lists[typeof(TEntity).Name];
        }

        #region IRepository<TEntity>成員
        public void SetDbContext(IUnitOfWork unitOfWork)
        {
            throw new NotImplementedException();
        }

        public void Insert(TEntity item)
        {
            if (item != null)
              {
                redisTypedClient.AddItemToList(table, item);
                redisDB.Save();
              }

        }

        public void Delete(TEntity item)
        {
            if (item != null)
            {
                var entity = Find(item.RootID);
                redisTypedClient.RemoveItemFromList(table, entity);
                redisDB.Save();
            }
        }

        public void Update(TEntity item)
        {
            if (item != null)
            {
                var old = Find(item.RootID);
                if (old != null)
                {
                    redisTypedClient.RemoveItemFromList(table, old);
                    redisTypedClient.AddItemToList(table, item);
                    redisDB.Save();
                }
            }
        }

        public IQueryable<TEntity> GetModel()
        {
            return table.GetAll().AsQueryable();
        }

        public TEntity Find(params object[] id)
        {
            return table.Where(i => i.RootID == (string)id[0]).FirstOrDefault();
        }
        #endregion

        #region IDisposable成員
        public void Dispose()
        {
            this.ExplicitDispose();
        }
        #endregion

        #region Protected Methods

        /// <summary>
        /// Provides the facility that disposes the object in an explicit manner,
        /// preventing the Finalizer from being called after the object has been
        /// disposed explicitly.
        /// </summary>
        protected void ExplicitDispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected void Dispose(bool disposing)
        {
            if (disposing)//清除非托管資源
            {
                table = null;
                redisTypedClient = null;
                redisDB.Dispose();
            }
        }
        #endregion

        #region Finalization Constructs
        /// <summary>
        /// Finalizes the object.
        /// </summary>
        ~RedisRepository()
        {
            this.Dispose(false);
        }
        #endregion
    }
}      

下面是在控制台中進行倉儲的調用

      IRepository<Car> repository = new Redis.Data.Core.RedisRepository<Car>();
            repository.Insert(new Car { ID = 3, Name = "占" });
            var entity = repository.GetModel().Where(i => i.ID == 3).FirstOrDefault();
            entity.Name = "修改了";
            repository.Update(entity);
            repository.GetModel().ToList().ForEach(e =>
            {
                Console.WriteLine(e.ID + "/" + e.RootID + "/" + e.Name);
            });      

下面是實作的結果的截圖

作者:倉儲大叔,張占嶺,

榮譽:微軟MVP

QQ:853066980

支付寶掃一掃,為大叔打賞!

Redis學習筆記~是時候為Redis實作一個倉儲了,RedisRepository來了