首页 > 代码库 > StackService.Redis 应用

StackService.Redis 应用

如今StackService.Redis已经转向商业版本。4.0以下的低版本依然免费和开源。

吴双,Redis系列命令拾遗分享  http://www.cnblogs.com/tdws/tag/NoSql/

可以在NuGet中获取StackExchange.Redis类库

        static void Main(string[] args)
        {
            Task.Run(() => SetRedis());
            //GetRedis();
           // Task.Run(() => GetRedis());
            Console.ReadKey();
        }

        /// <summary>
        /// 获取ConnectionMultiplexer
        /// </summary>
        /// <returns></returns>
        public static ConnectionMultiplexer TredisInfo()
        {
            ConfigurationOptions options = new ConfigurationOptions();
            options.EndPoints.Add("xxx.xxx.x.xx:7000");
            options.EndPoints.Add("xxx.xxx.x.xx:7001");
            options.EndPoints.Add("xxx.xxx.x.xx:7002");
            options.EndPoints.Add("xxx.xxx.x.xx:7003");
            options.EndPoints.Add("xxx.xxx.x.xx:7004");
            options.EndPoints.Add("xxx.xxx.x.xx:7005");
            var redisClient = ConnectionMultiplexer.Connect(options);
            return redisClient;
        }

        /// <summary>
        /// 获取redis存储数据
        /// </summary>
        public static void  GetRedis()
        {
            try
            {
                var multiplexer = TredisInfo();
                var client = multiplexer.GetDatabase();
                for (int i = 0; i < 600; i++)
                {
                    var result =  client.StringGet("TCP-" + i);
                    Console.WriteLine(result);
                    Thread.Sleep(10);
                }
                multiplexer.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
     
        }

        /// <summary>
        /// 向redis中存入数据
        /// </summary>
        /// <returns></returns>
        public static async Task SetRedis()
        {
            try
            {
                var multiplexer = TredisInfo();
                var client = multiplexer.GetDatabase();
                for (int i = 0; i < 600; i++)
                {
                   await client.StringSetAsync("TCP-" + i, "beijing欢迎你" + i);
                    Thread.Sleep(30);
                }
                multiplexer.Dispose();
                Console.WriteLine("执行完毕");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

注意:redis集群进行大量数据处理时,需要进行线程休息,否则会出去错误

StackService.Redis 应用