Redis

此demo需引用ServiceStack.Redis程序包

  1. Redis连接
    public static class RedisHelper
    {
        private static readonly IRedisClientsManager Manager;

        static RedisHelper()
        {
            // 读取Redis主机IP配置信息
            string[] redisMasterHosts = ConfigurationManager.AppSettings["RedisServerIP"].Split(',');

            // 如果Redis服务器是主从配置,则还需要读取Redis Slave机的IP配置信息
            string[] redisSlaveHosts = null;
            var slaveConnection = ConfigurationManager.AppSettings["RedisSlaveServerIP"];
            if (!string.IsNullOrWhiteSpace(slaveConnection))
            {
                redisSlaveHosts = slaveConnection.Split(',');
            }

            // 读取RedisDefaultDb配置
            int defaultDb = 0;
            string defaultDbSetting = ConfigurationManager.AppSettings["RedisDefaultDb"];
            if (!string.IsNullOrWhiteSpace(defaultDbSetting))
            {
                int.TryParse(defaultDbSetting, out defaultDb);
            }

            var redisClientManagerConfig = new RedisClientManagerConfig
            {
                MaxReadPoolSize = 50,
                MaxWritePoolSize = 50,
                DefaultDb = defaultDb
            };

            // 创建Redis连接池
            Manager = new PooledRedisClientManager(redisMasterHosts, redisSlaveHosts, redisClientManagerConfig)
            {
                PoolTimeout = 2000,
                ConnectTimeout = 500                
            };
        }

        /// <summary>
        /// 创建Redis连接
        /// </summary>
        /// <returns></returns>
        public static IRedisClient GetRedisClient()
        {
            var client = Manager.GetClient();
            return client;
        }
    }
  1. Redis 字符串
    public static void Main(string[] args)
    {
        Console.WriteLine("-----------------String------------------");

        using (var client = RedisHelper.GetRedisClient())
        {
            // 保存一个字符串
            const string key = "150101:name";
            client.SetValue(key, "Jack", TimeSpan.FromMinutes(5));
            Console.WriteLine("{0}的值是:{1}", key, client.GetValue(key));

            Console.ReadLine();

            // 保存一个对象
            var newPerson = new PersonModel { Id = 1, Name = "Jack", Age = 19, Telephone = "87976562" };
            var personKey = "150101:person:1";
            client.Set<PersonModel>(personKey, newPerson, TimeSpan.FromMinutes(5));
            Console.WriteLine("{0}的值是:", personKey);
            client.Get<PersonModel>(personKey).PrintDump();

            Console.ReadLine();

            // 整数自增/自减
            const string counterKey = "150101:counter";
            client.SetValue(counterKey, "12");

            client.IncrementValue(counterKey).Print();
            client.IncrementValueBy(counterKey, 5).Print();

            client.DecrementValue(counterKey).Print();
            client.DecrementValueBy(counterKey, 12).Print();
        }

        Console.ReadLine();
    }

    public class PersonModel
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Telephone { get; set; }
    }
  1. Redis 哈希

     public static void Main(string[] args)
     {
         Console.WriteLine("-----------------------Hash-------------------------");
    
         using (var client = RedisHelper.GetRedisClient())
         {
             var article = new ArticleModel
             {
                 Id = 18,
                 Title = "滴滴出行悄然提价 中国打车市场补贴战或将终结",
                 Views = 10,
                 Favourites = 0
             };
             const string articleKey = "150101:article:18";
    
             // 设置Hash中的多个字段
             client.SetRangeInHash(articleKey, article.ToStringDictionary());
             client.GetAllEntriesFromHash(articleKey).PrintDump();
    
             // 设置Hash中的单个字段
             client.SetEntryInHash(articleKey, "Content", "测试文章内容");
             client.GetAllEntriesFromHash(articleKey).PrintDump();
    
             // 对Hash中整数类型的字段做自增操作
             client.IncrementValueInHash(articleKey, "Views", 1).Print();
    
             client.GetAllEntriesFromHash(articleKey).PrintDump();
         }
    
         Console.ReadLine();
     }
  2. Redis 列表

    /// <summary>
    /// 新增,修改
    /// </summary>
    public static void Save()
    {
        using (var client = RedisHelper.GetRedisClient())
        {
            const string namesKey = "150101:savenames";

            // 单个元素添加到List尾部
            client.AddItemToList(namesKey, "Jack");
            Console.WriteLine("单个元素添加在List尾部:");
            client.GetAllItemsFromList(namesKey).PrintDump();

            // 多个元素添加到List尾部
            client.AddRangeToList(namesKey, new List<string> { "Jane", "Jim", "Joe" });
            Console.WriteLine("多个元素添加在List尾部:");
            client.GetAllItemsFromList(namesKey).PrintDump();

            // 单个元素添加到List头部
            client.PrependItemToList(namesKey, "Catherine");
            Console.WriteLine("在起始位置添加单个元素:");
            client.GetAllItemsFromList(namesKey).PrintDump();

            // 多个元素添加到List头部
            client.PrependRangeToList(namesKey, new List<string> { "Tom", "Tim" });
            Console.WriteLine("在起始位置添加多个元素:");
            client.GetAllItemsFromList(namesKey).PrintDump();

            // 根据指定索引设置元素的值
            client.SetItemInList(namesKey, 3, "Chloe");
            Console.WriteLine("修改第4个元素的值:");
            client.GetAllItemsFromList(namesKey).PrintDump();
        }            
    }

    /// <summary>
    /// 查询
    /// </summary>
    public static void Query()
    {
        using (var client = RedisHelper.GetRedisClient())
        {
            const string key = "150101:querynames";

            client.AddRangeToList(key, new List<string> { "Dick", "Evan", "Ada", "Florance", "Jane", "Bob", "Jim", "Joe", "Catherine" });
            client.GetAllItemsFromList(key).PrintDump();

            Console.WriteLine("List的长度是:{0}", client.GetListCount(key));

            Console.WriteLine("第5个元素是:{0}", client.GetItemFromList(key, 4));

            Console.WriteLine("从第4个到第7个元素:");
            client.GetRangeFromList(key, 3, 6).PrintDump();

            Console.WriteLine("排序之后的第3个到第9个元素:");
            client.GetRangeFromSortedList(key, 2, 8).PrintDump();
        }            
    }

    /// <summary>
    /// 删除
    /// </summary>
    public static void Remove()
    {
        using (var client = RedisHelper.GetRedisClient())
        {
            const string key = "150101:removenames";
            client.AddRangeToList(key, new List<string> { "Ada", "Bob", "Catherine", "Dick", "Evan", "Florance", "Jane", "Jim", "Joe" });
            client.GetAllItemsFromList(key).PrintDump();

            client.RemoveItemFromList(key, "Jane");
            Console.WriteLine("删除'Jane':");
            client.GetAllItemsFromList(key).PrintDump();

            var startItem = client.RemoveStartFromList(key);
            Console.WriteLine("删除起始元素:{0}", startItem);                
            client.GetAllItemsFromList(key).PrintDump();

            var endItem = client.RemoveEndFromList(key);
            Console.WriteLine("删除末尾元素:{0}", endItem);               
            client.GetAllItemsFromList(key).PrintDump();

            Console.WriteLine("删除所有元素");
            client.RemoveAllFromList(key);
            client.GetAllItemsFromList(key).PrintDump();
        }
    }    
  1. Redis 集合
    public static void Main()
    {
        Console.WriteLine("------------------Set--------------------");

        using (var client = RedisHelper.GetRedisClient())
        {
            const string key = "150101:ids";

            // 添加单个元素
            client.AddItemToSet(key, "12");
            client.GetAllItemsFromSet(key).PrintDump();

            // 添加多个元素
            client.AddRangeToSet(key, new List<string> { "14", "16", "15", "17", "12", "13" });
            client.GetAllItemsFromSet(key).PrintDump();

            Console.WriteLine("Set中是否包含'18':{0}", client.SetContainsItem(key, "18"));
            Console.WriteLine("Set中是否包含'16':{0}", client.SetContainsItem(key, "16"));

            Console.WriteLine("从Set中随机获取一个元素:{0}", client.GetRandomItemFromSet(key));

            Console.WriteLine("从Set中随机移除并返回被移除的这个元素:{0}", client.PopItemFromSet(key));

            const string key1 = "150101:ids1";
            client.AddRangeToSet(key1, new List<string> { "18", "19", "11", "2", "15" });

            // 取几个集合的交集
            client.GetIntersectFromSets(key, key1).PrintDump();
            // 取几个集合的并集
            client.GetUnionFromSets(key, key1).PrintDump();
        }

        Console.ReadLine();
    }
  1. Redis 有序集合
    public static void Main()
    {
        Console.WriteLine("-----------------------Sorted Set----------------------");

        using (var client = RedisHelper.GetRedisClient())
        {
            const string key = "150101:students";

            // 添加单个
            client.AddItemToSortedSet(key, "Jack", 96);
            client.GetAllItemsFromSortedSet(key).PrintDump();

            // 添加多个
            client.AddRangeToSortedSet(key, new List<string> { "Jane", "Jim", "Tony", "Mary", "Catherine" }, 92);

            // 获取所有元素
            Console.WriteLine("获取Sorted Set中的所有元素:");
            client.GetAllItemsFromSortedSet(key).PrintDump();

            // 获取指定范围内的元素,并且包含元素的score
            Console.WriteLine("获取指定范围的元素(包含score):");
            client.GetRangeWithScoresFromSortedSet(key, 1, 8).PrintDump();
        }

        Console.ReadLine();
    }
  1. 事务
    /// <summary>
    /// 事务
    /// </summary>
    private static void Transaction()
    {
        Console.WriteLine("---------------------Transaction----------------------");

        using (var client = RedisHelper.GetRedisClient())
        {                
            //bool somethingWrong = false;
            bool somethingWrong = true;
            const string stringKey = "150101:tran:string";
            const string hashKey = "150101:tran:hash";
            const string listKey = "150101:tran:list";

            using (var transaction = client.CreateTransaction())
            {
                try
                {
                    transaction.QueueCommand(cli => cli.SetValue(stringKey, "teststring", TimeSpan.FromSeconds(180)));
                    transaction.QueueCommand(cli => cli.SetEntryInHash(hashKey, "hashfield", "hashvalue"));
                    transaction.QueueCommand(cli => cli.AddItemToList(listKey, "listitem1"));
                    if (somethingWrong) throw new Exception();

                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                }
            }

            Console.WriteLine("{0}的值为:{1}", stringKey, client.GetValue(stringKey));
            Console.WriteLine("{0}的元素:{1}", hashKey, client.GetAllEntriesFromHash(hashKey).Dump());
            Console.WriteLine("{0}的元素:{1}", listKey, client.GetAllItemsFromList(listKey).Dump());
        }
    }
  1. 管道
    /// <summary>
    /// 管道
    /// Redis 管道技术可以在服务端未响应时,客户端可以继续向服务端发送请求,并最终一次性读取所有服务端的响应。
    /// 提高服务性能
    /// </summary>
    private static void Pipelining()
    {
        Console.WriteLine("---------------------Pipelining----------------------");

        using (var client = RedisHelper.GetRedisClient())
        {
            const string stringKey = "150101:pipeline:string";
            const string setKey = "150101:pipeline:set";

            using (var pipeline = client.CreatePipeline())
            {
                pipeline.QueueCommand(cli => cli.SetValue(stringKey, "stringvalue"));
                pipeline.QueueCommand(cli => cli.AddItemToSet(setKey, "12"));

                pipeline.Flush();
            }

            Console.WriteLine("{0}的值为:{1}", stringKey, client.GetValue(stringKey));
            Console.WriteLine("{0}的元素:{1}", setKey, client.GetAllItemsFromSet(setKey).Dump());
        }
    }
  1. GEO
    /// <summary>
    /// 地理信息
    /// </summary>
    private static void Geo()
    {
        using (var client = RedisHelper.GetRedisClient())
        {
            const string key = "150101:cities";

            client.AddGeoMembers(key, new[]
            {
                new RedisGeo(113.14, 23.08, "广州"),
                new RedisGeo(113.06, 23.02, "佛山"),
                new RedisGeo(114.22, 23.05, "惠州"),
                new RedisGeo(114.07, 22.33, "深圳"),
                new RedisGeo(113.34, 22.17, "珠海"),
                new RedisGeo(117.17, 31.52, "合肥"),
                new RedisGeo(116.24, 39.55, "北京"),
                new RedisGeo(103.51, 36.04, "兰州"),
                new RedisGeo(106.42, 26.35, "贵阳"),
                new RedisGeo(110.20, 20.02, "海口"),
                new RedisGeo(114.30, 38.02, "石家庄"),
                new RedisGeo(113.40, 34.46, "郑州"),
                new RedisGeo(126.36, 45.44, "哈尔滨"),
                new RedisGeo(114.17, 30.35, "武汉"),
                new RedisGeo(112.59, 28.12, "长沙"),
                new RedisGeo(125.19, 43.54, "长春"),
                new RedisGeo(118.46, 32.03, "南京"),
                new RedisGeo(115.55, 28.40, "南昌"),
                new RedisGeo(123.25, 41.48, "沈阳"),
                new RedisGeo(101.48, 36.38, "西宁"),
                new RedisGeo(117, 36.40, "济南"),
                new RedisGeo(112.33, 37.54, "太原"),
                new RedisGeo(108.57, 34.17, "西安"),
                new RedisGeo(121.29, 31.14, "上海"),
                new RedisGeo(104.04, 30.40, "成都"),
                new RedisGeo(117.12, 39.02, "天津"),
                new RedisGeo(91.08, 29.39, "拉萨"),
                new RedisGeo(87.36, 43.35, "乌鲁木齐"),
                new RedisGeo(102.42, 25.04, "昆明"),
                new RedisGeo(120.10, 30.16, "杭州"),
                new RedisGeo(106.33, 29.35, "重庆"),
            });

            Console.Write("武汉到广州的距离为:");
            var distance = client.CalculateDistanceBetweenGeoMembers(key, "武汉", "广州", "km");
            Console.WriteLine("{0}公里", distance);

            Console.WriteLine("查找武汉周围1000公里范围内的城市:");
            client.FindGeoMembersInRadius(key, "武汉", 1000, "km").PrintDump();

            Console.WriteLine("查找武汉周边500公里范围内的城市,并显示距离,且按照距离排序:");
            var geoResults = client.FindGeoResultsInRadius(key, "武汉", 500, "km", sortByNearest: true);
            geoResults.Select(i => new
            {
                i.Member,
                Distance = i.Distance + i.Unit
            }).ToArray().PrintDump();
        }
    }
  1. 分布式锁
    /// <summary>
    /// 分布式锁
    /// </summary>
    private static void Redlock()
    {
        using (var client = RedisHelper.GetRedisClient())
        {
            const string key = "150101:locker";
            const string counterKey = "150101:counter";

            client.SetValue(counterKey, "56");
            using (client.AcquireLock(key, TimeSpan.FromSeconds(10)))
            {
                client.SetValue(counterKey, "85");
                client.GetValue(counterKey).Print();
            }
        }
    }

11.

全部评论

相关推荐

11-09 11:01
济南大学 Java
Java抽象带篮子:外卖项目真得美化一下,可以看看我的详细的外卖话术帖子
点赞 评论 收藏
分享
11-18 15:57
门头沟学院 Java
最终归宿是测开:这个重邮的大佬在重邮很有名的,他就喜欢打92的脸,越有人质疑他,他越觉得爽😂
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务