Redis系列2- C#中使用Redis的示例

上一篇Redis的系列已经讲了Redis的下载、安装,接下来这一篇,主要讲使用Redis提供的 ServiceStack.Redis 这个开发库在C#项目中作为缓存服务使用的一个简单示例,废话不多话,直接上代码。



        private void TestRedis()
        {
            var Redis = new RedisClient("localhost"); //创建Redis实例(主机名根据项目的实际情况设置,可以使用配置文件的形式配置)

            var records = new List<TestInfo>();

            /*****操作泛型数据*******/
            if (Redis.Exists("TestInfos") <= 0) //判断某个缓存是否存在
            {
                //添加泛型集合数据
                Redis.Set("TestInfos", new List<TestInfo>()
                {
                    new TestInfo() { id = 1, name = "11" },
                    new TestInfo() { id = 2, name = "22" },
                    new TestInfo() { id = 3, name = "33" },
                    new TestInfo() { id = 4, name = "44" }
                });
                Redis.Expire("TestInfos", 60); //设置为一分钟过期
            }
            records = Redis.Get<List<TestInfo>>("TestInfos"); //获取Redis的缓存数据
            //Redis.Remove("TestInfos"); //删除一个缓存
            //records = Redis.Get<List<TestInfo>>("TestInfos"); //删除后尝试重新获取,结果为null(Redis中获取不存在的引用类型时返回null)
            /*****操作泛型数据*******/

            /*****链表操作*******/
            var testRedisList = Redis.As<TestInfo>();
            IRedisList<TestInfo> testData = testRedisList.Lists["testData"]; //指定一个链表
            Redis.Expire("testData", 60);  //设置为一分钟过期
            testData.AddRange(records); //添加数据
            testRedisList.Save(); //保存链表数据
            var testDataList = Redis.As<TestInfo>().Lists["testData"].ToList(); //获取链表数据
            /*****链表操作*******/

            /*****操作int类型数据*******/
            if (Redis.Exists("TestInt") <= 0) 
            {
                Redis.Set("TestInt", 11); //保存一个int类型的缓步数据
            }
            var recordStr = Redis.Get<int>("TestInt"); //获取数据
            Redis.Remove("TestInt"); //删除一个缓存
            var redisIntVal = Redis.Get<int>("TestInt"); //删除后尝试重新获取,结果为0(Redis中获取不存在的值类型时返回默认值)
            /*****操作int类型数据*******/
        }

  

 
posted @ 2018-02-23 11:06  justinwujian  阅读(613)  评论(1编辑  收藏  举报