C#使用Redis缓存,window下安装及C#代码基本操作

首先下载redis

下载地址:https://github.com/MSOpenTech/redis/releases

下载完后解压到c盘的redis文件夹下

打开一个 cmd 窗口 使用cd命令切换目录到 C:\redis 运行 redis-server.exe redis.windows.conf

这时候另启一个cmd窗口,原来的不要关闭,不然就无法访问服务端了。

切换到redis目录下运行 redis-cli.exe -h 127.0.0.1 -p 6379 。

设置键值对 set hellow 666

取出键值对 get hellow

 

 

成功运行后可以去服务管理器检查一下Redis是否正常运行

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

在c#中运行redis代码,首先需要dll支持

https://github.com/ServiceStack/ServiceStack.Redis 

当然也可以用nuget包搜索redis第一个就是啦,

用vs创建一个控制台程序:

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

RedisCacheHelper.Add("hellow redis", "redis-test", DateTime.Now.AddDays(1));

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

string str3 = RedisCacheHelper.Get<string>("hellow redis");

Console.WriteLine(str3);

RedisCacheHelper.Remove("wang");
string str = RedisCacheHelper.Get<string>("wang");
Console.WriteLine(str == null ? "未找到" : str);


Console.ReadKey();
}

 

接下来新建一个redis的帮助类

 public class RedisCacheHelper
    {
        private static readonly PooledRedisClientManager pool = null;
        private static readonly string[] redisHosts = null;
        public static int RedisMaxReadPool = 3;
        public static int RedisMaxWritePool = 1;

        static RedisCacheHelper()
        {
            var redisHostStr = "127.0.0.1:6379";

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

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

        #region Add
        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;
        }
        #endregion

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

接下来运行控制台

之前添加了一个key为"wang"的数据,把它移除后再获取,则缓存为空

去redis的客户端看一下,数据已成功操作啦

 

自己记录一下,省的自己忘记= =

posted @ 2018-07-25 12:01  余生很长_慢慢说  阅读(273)  评论(0编辑  收藏  举报