Redis在.net中的使用(2).net專案中的Redis使用

龐順龍發表於2019-05-11

Redis在.net中的使用(2).net專案中的Redis使用

Redis官網提供了很多開源的C#客戶端:Nhiredis ,ServiceStack.Redis ,StackExchange.Redis等。其中ServiceStack.Redis應該算是比較流行的。它提供了一整套從Redis資料結構都強型別物件轉換的機制並將物件json序列化。所以這裡只介紹ServiceStack.Redis,它也是目前產品中經常使用的客戶端。 

1、新建控制檯程式(略過)

2、新增ServiceStack.Redis,可以使用nuget新增,我這裡直接演示,用的以前的lib包



3、建立一個簡單的RedisCacheHelper操作類

public class RedisCacheHelper
{
    private static readonly PooledRedisClientManager pool = null;
    private static readonly string[] redisHosts = null;
    public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);
    public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);

    static RedisCacheHelper()
    {
        var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];

        if (!string.IsNullOrEmpty(redisHostStr))
        {
            redisHosts = redisHostStr.Split(',');

            if (redisHosts.Length > 0)
            {
                pool = new PooledRedisClientManager(redisHosts, redisHosts,
                    new RedisClientManagerConfig()
                    {
                        MaxWritePoolSize = RedisMaxWritePool,
                        MaxReadPoolSize = RedisMaxReadPool,
                        AutoStart = true
                    });
            }
        }
    }

    public static void Add<T>(string key, T value, DateTime expiry)
    {
        if (value == null)
        {
            return;
        }

        if (expiry <= DateTime.Now)
        {
            Remove(key);

            return;
        }

        try
        {
            if (pool != null)
            {
                using (var r = pool.GetClient())
                {
                    if (r != null)
                    {
                        r.SendTimeout = 1000;
                        r.Set(key, value, expiry - DateTime.Now);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "儲存", key);
        }

    }

    public static void Add<T>(string key, T value, TimeSpan slidingExpiration)
    {
        if (value == null)
        {
            return;
        }

        if (slidingExpiration.TotalSeconds <= 0)
        {
            Remove(key);

            return;
        }

        try
        {
            if (pool != null)
            {
                using (var r = pool.GetClient())
                {
                    if (r != null)
                    {
                        r.SendTimeout = 1000;
                        r.Set(key, value, slidingExpiration);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "儲存", key);
        }

    }
     
    public static T Get<T>(string key)
    {
        if (string.IsNullOrEmpty(key))
        {
            return default(T);
        }

        T obj = default(T);

        try
        {
            if (pool != null)
            {
                using (var r = pool.GetClient())
                {
                    if (r != null)
                    {
                        r.SendTimeout = 1000;
                        obj = r.Get<T>(key);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "獲取", key);
        }


        return obj;
    }

    public static void Remove(string key)
    {
        try
        {
            if (pool != null)
            {
                using (var r = pool.GetClient())
                {
                    if (r != null)
                    {
                        r.SendTimeout = 1000;
                        r.Remove(key);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "刪除", key);
        }

    }

    public static bool Exists(string key)
    {
        try
        {
            if (pool != null)
            {
                using (var r = pool.GetClient())
                {
                    if (r != null)
                    {
                        r.SendTimeout = 1000;
                        return r.ContainsKey(key);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "是否存在", key);
        }

        return false;
    }

}
4、專案配置檔案


  <appSettings>
    <add key="SessionExpireMinutes" value="180" />
    <add key="redis_server_session" value="127.0.0.1:6379" />
    <add key="redis_max_read_pool" value="3" />
    <add key="redis_max_write_pool" value="1" />
  </appSettings>
5、簡單測試,注意要保證redis服務處於啟動狀態




請喊我大龍哥最後編輯於:3年前

內容均為作者獨立觀點,不代表八零IT人立場,如涉及侵權,請及時告知。

相關文章