Redis緩存服務搭建及實現數據讀寫

發現博客園中好多大牛在介紹本身的開源項目是不多用到緩存,好比Memcached、Redis、mongodb等,今天得空抽時間把Redis緩存研究了一下,寫下來總結一下,跟你們一塊兒分享 一下。因爲小弟水平有限又是第一次接觸Redis,有些的不對的地方歡迎指出糾正。git

一、  下載安裝Redisgithub

下載地址:https://github.com/MSOpenTech/Redisredis

二、  安裝Redismongodb

     在下載的文件中找到bin並打開。數據庫

  

  • redis-server.exe:服務程序(目前咱們只用到這一個)
  • redis-check-dump.exe:本地數據庫檢查
  •  redis-check-aof.exe:更新日誌檢查
  •  redis-benchmark.exe:性能測試,用以模擬同時由N個客戶端發送M個 SETs/GETs 查詢 (相似於 Apache 的ab 工具).

Redis有不少配置參數,這裏就不介紹了,有興趣的朋友能夠到網上查查。緩存

雙擊redis-server.exe或者在命令窗口中輸入D:\redis-2.6\redis-server.exe便可啓動Redis服務。函數

 

 注意端口號:Port:6379 在咱們的程序中會用到該端口號。工具

三、  數據讀、寫、刪測試,並實現list存數。性能

首先引用下面四個DLL文件學習

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ServiceStack.Redis;
using ServiceStack.Text;
using ServiceStack.Redis.Generic;

namespace RedisStudy
{
    public class RedisHelper:IDisposable
    {
        public RedisClient Redis = new RedisClient("127.0.0.1", 6379);
        //緩存池
        PooledRedisClientManager prcm = new PooledRedisClientManager();
        
        //默認緩存過時時間單位秒
        public int secondsTimeOut = 30 * 60;
       
        /// <summary>
        /// 緩衝池
        /// </summary>
        /// <param name="readWriteHosts"></param>
        /// <param name="readOnlyHosts"></param>
        /// <returns></returns>
        public static PooledRedisClientManager CreateManager(
         string[] readWriteHosts, string[] readOnlyHosts)
        {
            return new PooledRedisClientManager(readWriteHosts, readOnlyHosts,
                new RedisClientManagerConfig
                {
                    MaxWritePoolSize = readWriteHosts.Length * 5,
                    MaxReadPoolSize = readOnlyHosts.Length * 5,
                    AutoStart = true,
                });// { RedisClientFactory = (IRedisClientFactory)RedisCacheClientFactory.Instance.CreateRedisClient("127.0.0.1", 6379) };           
        }
        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="OpenPooledRedis">是否開啓緩衝池</param>
        public RedisHelper(bool OpenPooledRedis=false)
        {
            
            if (OpenPooledRedis)
            {
                prcm = CreateManager(new string[] { "127.0.0.1:6379" }, new string[] { "127.0.0.1:6379" });
                Redis = prcm.GetClient() as RedisClient;
            }
        }

        #region Key/Value存儲
        /// <summary>
        /// 設置緩存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">緩存建</param>
        /// <param name="t">緩存值</param>
        /// <param name="timeout">過時時間,單位秒,-1:不過時,0:默認過時時間</param>
        /// <returns></returns>
        public bool Set<T>(string key, T t, int timeout = 0)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }
            
            return Redis.Add<T>(key, t);
        }
        /// <summary>
        /// 獲取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            return Redis.Get<T>(key);
        }
        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            return Redis.Remove(key);
        }

        public bool Add<T>(string key, T t, int timeout)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }
            return Redis.Add<T>(key, t);
        }
        #endregion

        #region 鏈表操做
        /// <summary>
        /// 根據IEnumerable數據添加鏈表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="values"></param>
        /// <param name="timeout"></param>
        public void AddList<T>(string listId, IEnumerable<T> values, int timeout = 0)
        {
            Redis.Expire(listId,60);
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(listId, secondsTimeOut);
            }
            var redisList = iredisClient.Lists[listId];
            redisList.AddRange(values);
            iredisClient.Save();
        }
        /// <summary>
        /// 添加單個實體到鏈表中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="Item"></param>
        /// <param name="timeout"></param>
        public void AddEntityToList<T>(string listId, T Item, int timeout = 0)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(listId, secondsTimeOut);
            }
            var redisList = iredisClient.Lists[listId];
            redisList.Add(Item);
            iredisClient.Save();
        }
        /// <summary>
        /// 獲取鏈表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <returns></returns>
        public IEnumerable<T> GetList<T>(string listId)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            return iredisClient.Lists[listId];
        }
        /// <summary>
        /// 在鏈表中刪除單個實體
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="t"></param>
        public void RemoveEntityFromList<T>(string listId, T t)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            var redisList = iredisClient.Lists[listId];
            redisList.RemoveValue(t);
            iredisClient.Save();
        }
        /// <summary>
        /// 根據lambada表達式刪除符合條件的實體
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="func"></param>
        public void RemoveEntityFromList<T>(string listId, Func<T,bool> func)
        {
            using (IRedisTypedClient<T> iredisClient = Redis.As<T>())
            {
                var redisList = iredisClient.Lists[listId];
                T value = redisList.Where(func).FirstOrDefault();
                redisList.RemoveValue(value);
                iredisClient.Save();
            }
        }
        #endregion
        //釋放資源
        public void Dispose()
        {
            if (Redis != null)
            {
                Redis.Dispose();
                Redis = null;
            }
            GC.Collect();

        }
    }
}

 

四、  測試

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace RedisStudy
{
    public class User
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }

    class Program
    {
        static RedisHelper redisHelper = new RedisHelper(true);
        
        static void Main(string[] args)
        {
            User u = new User() { Name = "eric1", Id = 1 };
            redisHelper.Set<User>("user", u);//設置緩存
            u=redisHelper.Get<User>("user");
            Console.WriteLine(u.Name);
            
            List<User> list = new List<User>()
            {
                new User(){Name="eric1",Id=1},
                 new User(){Name="eric2",Id=2}
            };
           
            redisHelper.Remove("list1");//刪除緩存
            redisHelper.AddList<User>("list1", list);//添加緩存鏈表
            redisHelper.AddEntityToList<User>("list1", new User() { Name = "eric3",Id=3 });
            list = redisHelper.GetList<User>("list1").ToList();
            Console.WriteLine(list.Count);

            redisHelper.RemoveEntityFromList<User>("list1", list[0]);
            redisHelper.RemoveEntityFromList<User>("list1", it => it.Id == 2);
            list = redisHelper.GetList<User>("list1").ToList();
            Console.WriteLine(list.Count);

            redisHelper.Dispose();
            Console.ReadLine();
             
        }

    }
}

 

整篇文章寫的比較倉促,不少基本點都沒有說明,有不懂的請百度一下。

若是你有好的學習NoSQl的資料歡迎交流。

Redis其餘操做,點擊查看

點擊下載源碼

相關文章
相關標籤/搜索