.net redis数据缓存(一) redis在Windows环境中的安装

来源:互联网 发布:珠宝设计绘图软件 编辑:程序博客网 时间:2024/06/05 07:48

写在前面的话:

   

正文:

 1、下载redis

地址:http://https://github.com/MicrosoftArchive/redis/releases


Windows下载msi或者zip都是可以的。msi会在path环境变量中配置变量,我一般下载的是zip的,我这里也是用zip的讲解,下载下来后解压会看到如下文件:



接下来,我们用cmd来运行redis服务器。看准我红框中的内容


回车以后,会看到如下画面,说明成功




接下来我们还有下载一个桌面redis工具,用来管理redis缓存,我这里推荐redis Desktop Manager

点击下载:https://redisdesktop.com/download

下载完成,连接到我们的redis服务器


我一般用的是一款中文的界面,可以查询群文件下载redis管理平台



接下来,我们通过一个简单的.net程序来入门一下redis,存取一下常见的类型

首先,我们要引用微软为我们封装好的 .net redis内库,我这里用的是ServiceStack.Redis,如下图引用这个内库文件,就可以开始我们的redis开发了。


我这里的案例用MVC5开发,后期,比较复杂类型的我会用webapi。


 废话不多说,直接上代码,看一下常见的string类型如何缓存

  public ActionResult Index()        {            string homeindex = string.Empty;            try            {                //连接redis服务器                // RedisClient()方法有四个字段 string host, int port, string password = null, long db = 0                // host为服务器ip地址、  port为端口、  password为密码,  db为缓存大小                var client = new RedisClient("127.0.0.1", 6379);                //redis存取其实首先应该先从redis服务器中取出来,如果redis服务器没有数据,则存入数据,我这里定义一个叫 homeindex 的key                //key值是绝对不能重复的                //key值是绝对不能重复的                //key值是绝对不能重复的                //重要的事情说三遍 ,key值是唯一的键                //首先读取我们储存的homeindex这个key                //取出的方法可以用 Get(key)、Get<T>(key) 、 GetAll<T>(IEnumerable<string> keys)等方式取出来                homeindex = client.Get<string>("homeindex");                if (string.IsNullOrEmpty(homeindex))//如果不存在,则添加这个key                {                    //string类型的缓存,set<T>为存储方式,支持string、int、bool、list等常见类型,返回bool类型                    //set<T> 有key, T value, DateTime expiresAt 和key, T value, TimeSpan expiresAt两种储存方式,                    //key为唯一键,value为值,DateTime和 TimeSpan都是过期时间 ,只是略有不同;                    //比如存储一天可以用 DateTime.Now.AddDays(1),也可以用 TimeSpan.FromDays(1)  。我建议用 TimeSpan类型                    //缓存homeindex值为 我的第一个redis,缓存时间1分钟                    bool flag = client.Set<string>("homeindex", "我的第一个redis", TimeSpan.FromMinutes(1));                    if (flag)  //当返回true说明存储成功 ,false存储失败                    {                        //以写日志为荣,以打断点为耻                        RedisLog.WriteRedisLogs("成功插入", RedisLog.LOG_TYPE.SuccessLog);                    }                    else                    {                        RedisLog.WriteRedisLogs("成功失败", RedisLog.LOG_TYPE.ExceLog);                    }                }                           }            catch (Exception ex)            {                RedisLog.WriteRedisLogs("发生异常:" + ex.Message, RedisLog.LOG_TYPE.ExceLog);            }                       ViewBag.homeindex = homeindex;            return View();        }    }

当代码运行以后,我们通过redis管理平台看看缓存到的数据如下:


可以看到我们缓存的数据已经成功缓存到的redis服务器中。下一篇,我将缓存一个List集合,用分页的形式展示数据。

阅读全文
0 0