首页 > 其他 > 详细

redis实现消息队列

时间:2018-07-10 12:17:53      阅读:212      评论:0      收藏:0      [点我收藏+]
        //版本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实现消息队列

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!