Redis

1.新建控制台应用程序,并引用redis相关dll文件,可以在NuGet包里找到

2.新建redis公共类,相当于工具类,话不多说直接上代码:

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;
        }


}

3.config相关配置代码

<appSettings>
    <!-- redis Start   -->
    <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" />
    <!--redis end-->
</appSettings>

4.Test控制台入口程序

static void Main(string[] args)
{
            Console.WriteLine("Redis写入缓存:搞事的");

            RedisCacheHelper.Add("搞事的", "去你妈", DateTime.Now.AddDays(1));//把可恶的内容写进去

            Console.WriteLine("Redis获取缓存:");

            string str3 = RedisCacheHelper.Get<string>("搞事的");//读取Key的value

            Console.WriteLine(str3);

            Console.WriteLine("Redis获取缓存:nihao");
            RedisCacheHelper.Add("nihao", "hello", DateTime.Now.AddDays(1));
            string str = RedisCacheHelper.Get<string>("nihao");
            Console.WriteLine(str);           

            Console.ReadKey();
}

5.当出现以下报错原因

由于目标计算机积极拒绝,无法连接。 127.0.0.1:6379

错误原因:redis服务没启动

解决方法:

<1> 需要先下载Redis-x64-3.0.503.msi,redis下载。

<2>安装redis

<3>安装完成之后,启动服务

6.下载并安装Redis-x64-3.0.503.msi,地址:https://github.com/MicrosoftArchive/redis/releases

7.安装完成后,启动服务,出现以下提示则安装成功:

posted @ 2019-01-02 14:42  CH|heyi  阅读(271)  评论(0编辑  收藏  举报