码迷,mamicode.com
首页 > 其他好文 > 详细

redis实现消息队列

时间:2018-07-10 12:46:50      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:log   cpu   color   对象   rem   read   客户   github   消息队列   

        //版本2:使用Redis的客户端管理器(对象池)
        public static IRedisClientsManager redisClientManager = new PooledRedisClientManager(
        new[]
        {
            // 读写链接

            //如果是Redis集群则配置多个{IP地址:端口号}即可
            "127.0.0.1:6379","10.0.0.1:6379","10.0.0.2:6379","10.0.0.3:6379"
        }, new[]
        {
            // 只读链接
            //如果是Redis集群则配置多个{IP地址:端口号}即可
            "127.0.0.1:6379","10.0.0.1:6379","10.0.0.2:6379","10.0.0.3:6379"
        }, 10);
        //从池中获取Redis客户端实例
        public static IRedisClient redisClient = redisClientManager.GetClient();

        static void Main(string[] args)
        {
            #region 客户端添加消息
            redisClient.EnqueueItemOnList("Log", "1111");
            redisClient.EnqueueItemOnList("Log", "222");
            redisClient.EnqueueItemOnList("Log", "333");
            #endregion

            #region 服务器端扫码消息
            ThreadPool.QueueUserWorkItem(o =>
               {
                   while (true)
                   {
                       try
                       {
                           if (redisClient.GetListCount("Log") > 0)
                           {
                               string log = redisClient.DequeueItemFromList("Log");
                               if (!string.IsNullOrEmpty(log))
                               {
                                   Console.WriteLine(log);
                               }
                           }
                           else
                           {
                               Thread.Sleep(1000); //为避免CPU空转,在队列为空时休息1秒
                           }
                       }
                       catch (Exception ex)
                       {
                           redisClient.EnqueueItemOnList("Log", ex.ToString());
                       }
                   }
               });
            #endregion

            Console.ReadLine();
        }

 github地址:https://github.com/842549829/RedisMessage

redis实现消息队列

标签:log   cpu   color   对象   rem   read   客户   github   消息队列   

原文地址:https://www.cnblogs.com/liuxiaoji/p/9288102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!