Exemple #1
0
        /// <summary>
        /// 配置队列线程
        /// </summary>
        private void ConfigQueueThread()
        {
            String appName = m_ConsumerConfig.ApplicationName;

            if (m_EsbConfig.ServiceConfig != null && m_EsbConfig.ServiceConfig.Count > 0)
            {
                //--根据QueueCenter的消费者配置文件中的ApplicationName找到和本机相关的配置文件
                List <EsbView_ServiceConfig> lstServcieConfig = m_EsbConfig.ServiceConfig.FindAll(x => {
                    return(!String.IsNullOrEmpty(x.QueueCenterUri) && appName.EndsWith(x.QueueCenterUri));
                });

                //--删除不应该由本机消费的队列并停用相关线程
                DeleteQueueThread(lstServcieConfig);

                //--添加本机应该消费的队列
                foreach (EsbView_ServiceConfig sc in lstServcieConfig)
                {
                    if (!m_QueueThreadDict.ContainsKey(sc.ServiceName))
                    {
                        RabbitMQClient rabbitMQ = new RabbitMQClient(m_ParamMQ[0], m_ParamMQ[2], m_ParamMQ[3], Int32.Parse(m_ParamMQ[1]));
                        QueueThread    qt       = new QueueThread(sc.ServiceName, rabbitMQ);
                        qt.Start();

                        m_QueueThreadDict[sc.ServiceName] = qt;
                    }
                }
            }
            else
            {
                //--删除不应该由本机消费的队列并停用相关线程
                DeleteQueueThread(null);
            }
        }
Exemple #2
0
        protected void InitRabbitClient()
        {
            client             = new RabbitMQClient("iClock Service Queue");
            client.OnRecieved += (model, message) =>
            {
                if (fingerPrinterManager != null && !string.IsNullOrEmpty(message))
                {
                    try
                    {
                        CommandObject command = client.JsonDeserialize(message);
                        switch (command.Command)
                        {
                        case MessageCommandEnum.DISCONNECT:
                        {
                            string ip = command.Data as string;
                            fingerPrinterManager.Disconnect(ip);
                            break;
                        }

                        case MessageCommandEnum.CONNECT:
                        {
                            string ip = command.Data as string;
                            fingerPrinterManager.Connect(ip);
                            break;
                        }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.Message, ex);
                    }
                }
            };
        }
        public IActionResult SendRegistration([FromBody] Register command)
        {
            try
            {
                var registration = new Register();
                using (var session = Store.LightweightSession())
                {
                    registration.Name    = command.Name;
                    registration.Address = command.Address;
                    registration.City    = command.City;
                    registration.Email   = command.Email;
                    session.Insert(registration);
                    session.SaveChanges();
                }

                RabbitMQClient client = new RabbitMQClient();
                client.SendRegistration(registration);
                client.Close();
                return(Ok(registration));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
        /// <summary>
        /// Create a new Message for Publishing to an Exchange
        /// </summary>
        /// <param name="client">A <see cref="RabbitMQClient"/> Instance</param>
        /// <param name="exchange">The Exchange to Publish this Message to</param>
        /// <param name="routingKey">The Routing Key for this Message</param>
        /// <param name="type">The Type of Message</param>
        /// <param name="mode">The Publishing Mode for this Message</param>
        /// <returns>A New <see cref="PublishMessage"/> Instance ready to be Customized before Publishing</returns>
        public static PublishMessage CreateNew(RabbitMQClient client, string exchange, string routingKey, string type = "", PublishMode mode = PublishMode.BrokerConfirm)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (exchange == null)
            {
                throw new ArgumentNullException(nameof(exchange));
            }

            if (routingKey == null)
            {
                throw new ArgumentNullException(nameof(routingKey));
            }

#if NETSTANDARD
            TimeSpan publishTimeout = client.DefaultPublishTimeout ?? TimeSpan.FromMilliseconds(client.HeartbeatInterval.TotalMilliseconds * 2);
#else
            TimeSpan publishTimeout = client.DefaultPublishTimeout ?? client.HeartbeatInterval.Multiply(2);
#endif

            return(new PublishMessage(client.DefaultPublishRetries)
            {
                Exchange = exchange,
                RoutingKey = routingKey,
                Mode = mode,
                Type = type,
                PublishTimeout = publishTimeout,
                PublishRetries = client.DefaultPublishRetries,
            });
        }
        public async Task CreatePublishAndConsume()
        {
            var connectionFactory = CreateConnectionFactory();

            using (var queueClient = new RabbitMQClient(connectionFactory))
            {
                var queueName = $"IntegratedTestQueue_{Guid.NewGuid()}";

                queueClient.EnsureQueueExists(queueName, autoDelete:true);

                queueClient.Publish("", queueName, "TestValue123");

                var receivedMessage = "";

                var worker = await SimpleMessageProcessingWorker<string>.CreateAndStartAsync(queueClient, queueName,
                    message => DoSomething(message, out receivedMessage), CancellationToken.None);

                const int timeLimit = 10000;

                var elapsedTime = 0;

                while (receivedMessage == "" && elapsedTime < timeLimit)
                {
                    await Task.Delay(100);
                    elapsedTime += 100;
                }

                worker.Stop();

                receivedMessage.ShouldBe("TestValue123");
            }
        }
        public async Task AdvancedCreatePublishAndConsume()
        {
            var connectionFactory = CreateConnectionFactory();

            using (var queueClient = new RabbitMQClient(connectionFactory))
            {
                var queueName = $"IntegratedTestQueue_{Guid.NewGuid()}";

                queueClient.EnsureQueueExists(queueName, autoDelete: true);

                queueClient.Publish("", queueName, "TestValue123");

                var receivedMessage = "";

                var worker = await AdvancedMessageProcessingWorker <string> .CreateAndStartAsync(queueClient, queueName,
                                                                                                 message => DoSomething(message, out receivedMessage), CancellationToken.None);

                const int timeLimit = 10000;

                var elapsedTime = 0;

                while (receivedMessage == "" && elapsedTime < timeLimit)
                {
                    await Task.Delay(100);

                    elapsedTime += 100;
                }

                worker.Stop();

                receivedMessage.ShouldBe("TestValue123");
            }
        }
        /// <summary>
        /// Create a new Message for Publishing a Reply directly to a Queue
        /// </summary>
        /// <param name="client">A <see cref="RabbitMQClient"/> Instance</param>
        /// <param name="replyTo">The Name of the Queue to Directly Publish to</param>
        /// <param name="receivedMessageId">The ID of the Message that is being Replied to</param>
        /// <param name="type">The Type of Message</param>
        /// <param name="mode">The Publishing Mode for this Message</param>
        /// <returns>A New <see cref="PublishMessage"/> Instance ready to be Customized before Publishing</returns>
        public static PublishMessage CreateNew(RabbitMQClient client, string replyTo, Guid receivedMessageId, string type = "", PublishMode mode = PublishMode.BrokerConfirm)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (replyTo == null)
            {
                throw new ArgumentNullException(nameof(replyTo));
            }

            if (receivedMessageId == Guid.Empty)
            {
                throw new ArgumentOutOfRangeException(nameof(receivedMessageId), "The Received Message ID cannot be an Empty GUID");
            }

#if NETSTANDARD
            TimeSpan publishTimeout = client.DefaultPublishTimeout ?? TimeSpan.FromMilliseconds(client.HeartbeatInterval.TotalMilliseconds * 2);
#else
            TimeSpan publishTimeout = client.DefaultPublishTimeout ?? client.HeartbeatInterval.Multiply(2);
#endif

            return(new PublishMessage(client.DefaultPublishRetries)
            {
                Exchange = "",
                RoutingKey = replyTo,
                Mode = mode,
                Type = type,
                PublishTimeout = publishTimeout,
                PublishRetries = client.DefaultPublishRetries,
                CorrelationID = receivedMessageId,
            });
        }
        public async Task DelayedPublish()
        {
            var connectionFactory = CreateConnectionFactory();

            using (var queueClient = new RabbitMQClient(connectionFactory))
            {
                var queueName = $"IntegratedTestQueue_{Guid.NewGuid()}";

                try
                {
                    queueClient.QueueDeclare(queueName);
                    queueClient.ExchangeDeclare("delayedTargetExchange");
                    queueClient.QueueBind(queueName, "delayedTargetExchange", "delayedTargetRoutingKey");

                    queueClient.DelayedPublish("delayedTargetExchange", "delayedTargetRoutingKey", "delayedMessage",
                                               TimeSpan.FromSeconds(5));

                    queueClient.GetMessageCount(queueName).ShouldBe <uint>(0);

                    await Task.Delay(TimeSpan.FromSeconds(5));

                    queueClient.GetMessageCount(queueName).ShouldBe <uint>(1);
                }
                finally
                {
                    queueClient.QueueDelete(queueName);
                }
            }
        }
        public IHttpActionResult GenerateFibonacciSeries([FromBody] FibonacciRange req)
        {
            try
            {
                RabbitMQClient client = new RabbitMQClient();

                GenerateFibonacciPosRange fr = new GenerateFibonacciPosRange();
                BigInteger[] results         = new BigInteger[req.EndPosition - req.StartPosition + 1];
                results = fr.GetSeriesBetweenPosition(req.StartPosition, req.EndPosition);
                foreach (decimal num in results)
                {
                    req.result += num.ToString() + ", ";
                }
                //req.result = results.ToString();
                client.SendFibonacciSeries(req);

                client.Close();
            }
            catch (Exception)
            {
                return(StatusCode(HttpStatusCode.BadRequest));
            }

            return(Ok(req));
        }
Exemple #10
0
        static void Main(string[] args)
        {
            //SendPayment(payment);
            //ClientListen(payment);

            Console.WriteLine("[+] Starting...");
            cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName  = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            ramCounter = new PerformanceCounter("Memory", "Available MBytes");

            client = new RabbitMQClient(conversationId);
            try
            {
                System.Timers.Timer t = new System.Timers.Timer(1200);
                t.Elapsed += new ElapsedEventHandler(TimerElapsed);
                t.Start();
                Thread.Sleep(10000);
            }
            catch (Exception e)
            {
                Console.WriteLine("catched exception");
            }
            Console.ReadLine();
        }
 void Awake()
 {
     taiwanMap     = FindObjectOfType <TaiwanMap>();
     terrain       = FindObjectOfType <Terrain>();
     messageBroker = FindObjectOfType <RabbitMQClient>();
     troopManager  = FindObjectOfType <TroopManager>();
     twTerrainCam  = FindObjectOfType <Camera>();
 }
 public SocialOryxlWSHandler(
     RabbitMQClient _rabbitMQClient,
     SocialMsgManager _socialMsgManager
     )
 {
     rabbitMQClient   = _rabbitMQClient;
     socialMsgManager = _socialMsgManager;
 }
 public IndexModel(IHostingEnvironment hostingEnvironment,
                   ImageService imageService,
                   RabbitMQClient mQClient)
 {
     _hostingEnvironment = hostingEnvironment;
     _imageService       = imageService;
     _mQClient           = mQClient;
 }
Exemple #14
0
        public IActionResult MakePayment([FromBody] CardPayment payment)
        {
            RabbitMQClient client = new RabbitMQClient();

            client.SendPayment(payment);
            client.Close();
            return(Ok(payment));
        }
Exemple #15
0
        public IActionResult MakePayment([FromBody] PurchaseOrder payment)
        {
            RabbitMQClient client = new RabbitMQClient();

            client.SendPurchaseOrder(payment);
            client.Close();
            return(Ok(payment));
        }
Exemple #16
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="serviceName"></param>
 public QueueThread(String serviceName, RabbitMQClient rabbitMQClient)
 {
     m_ServiceName = serviceName;
     m_RabbitMQ = rabbitMQClient;
     m_Thread = new Thread(x =>
     {
         ProcessInvokeQueueMessage();
     });
 }
 public WxqFuncController(OryxWebSocketPool _wsPool,
                          VoteAppDbContext _dbContext,
                          RabbitMQClient _rabbitMqClient
                          )
 {
     wsPool         = _wsPool;
     dbContext      = _dbContext;
     rabbitMqClient = _rabbitMqClient;
 }
        /// <summary>
        /// Create a new Message with Binary (byte) Content for Publishing a Reply directly to a Queue
        /// </summary>
        /// <param name="client">A <see cref="RabbitMQClient"/> Instance</param>
        /// <param name="replyTo">The Name of the Queue to Directly Publish to</param>
        /// <param name="receivedMessageId">The ID of the Message that is being Replied to</param>
        /// <param name="bytes">The Binary (byte) Data for this Message</param>
        /// <param name="type">The Type of Message</param>
        /// <param name="mode">The Publishing Mode for this Message</param>
        /// <returns>A New <see cref="BinaryPublishMessage"/> Instance ready to be Published</returns>
        public static PublishMessage CreateNew(RabbitMQClient client, string replyTo, Guid receivedMessageId, ReadOnlyMemory <byte> bytes, string type = "", PublishMode mode = PublishMode.BrokerConfirm)
        {
            PublishMessage message = CreateNew(client, replyTo, receivedMessageId, type, mode);

            message.Body        = bytes;
            message.ContentType = ContentTypes.Binary;

            return(message);
        }
        /// <summary>
        /// Create a new Message with Binary (byte) Content for Publishing to an Exchange
        /// </summary>
        /// <param name="client">A <see cref="RabbitMQClient"/> Instance</param>
        /// <param name="exchange">The Exchange to Publish this Message to</param>
        /// <param name="routingKey">The Routing Key for this Message</param>
        /// <param name="bytes">The Binary (byte) Data for this Message</param>
        /// <param name="type">The Type of Message</param>
        /// <param name="mode">The Publishing Mode for this Message</param>
        /// <returns>A New <see cref="BinaryPublishMessage"/> Instance ready to be Published</returns>
        public static PublishMessage CreateNew(RabbitMQClient client, string exchange, string routingKey, ReadOnlyMemory <byte> bytes, string type = "", PublishMode mode = PublishMode.BrokerConfirm)
        {
            PublishMessage message = CreateNew(client, exchange, routingKey, type, mode);

            message.Body        = bytes;
            message.ContentType = ContentTypes.Binary;

            return(message);
        }
Exemple #20
0
        static void Main(string[] args)
        {
            IRabbitMQClient client = new RabbitMQClient(new UriRabbitMqConfiguration("GPSLocation",
                                                                                     "amqp://*****:*****@clam.rmq.cloudamqp.com/kkxglvxw")
                                                        );

            client.ReceiveMessages(x => Console.WriteLine(x));
            Console.ReadKey();
        }
 public FingerprintsController()
 {
     fingerprintService = new FingerprintService();
     SERVER_IP          = ConfigurationManager.AppSettings["iClockHost"] ?? "10.62.0.23";
     if (_client == null)
     {
         _client = new RabbitMQClient("Fingerprint Monitor Queue");
     }
 }
Exemple #22
0
 public SocialMsgManager(
     IDistributedCache _distributedCache,
     OryxWebSocketPool _wsPool,
     RabbitMQClient _rabbitMQClient
     )
 {
     distributedCache = _distributedCache;
     wsPool           = _wsPool;
     rabbitMQClient   = _rabbitMQClient;
 }
Exemple #23
0
        static void Main(string[] args)
        {
            AdminRun.Run();

            if (!SetConsoleCtrlHandler(cancelHandler, true))
            {
                Console.WriteLine("程序监听系统按键异常");
            }
            try
            {
                //1.MEF初始化
                MefConfig.Init();

                //2.数据库初始化连接
                ConfigInit.InitConfig();

                //3.系统参数配置初始化
                ConfigManager configManager = MefConfig.TryResolve <ConfigManager>();
                configManager.Init();

                Console.Title         = SystemConfig.ProgramName;
                Console.CursorVisible = false; //隐藏光标

                //4.任务启动
                QuartzHelper.InitScheduler();
                QuartzHelper.StartScheduler();

                //5.加载SQL信息到缓存中
                XmlCommandManager.LoadCommnads(SysConfig.XmlCommandFolder);

                //测试dapper orm框架
                //DapperDemoService.Test();

                //启动站点
                using (NancyHost host = Startup.Start(SystemConfig.WebPort))
                {
                    //调用系统默认的浏览器
                    string url = string.Format("http://127.0.0.1:{0}", SystemConfig.WebPort);
                    Process.Start(url);
                    Console.WriteLine("系统已启动,当前监听站点地址:{0}", url);

                    //4.消息队列启动
                    RabbitMQClient.InitClient();

                    //5.系统命令初始化
                    CommandHelp.Init();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Console.Read();
        }
Exemple #24
0
        private void InitialiseProducer()
        {
            _rabbitClient = RabbitMQClient.Configure(x =>
            {
                x.HostName = HostName;
                x.Password = Password;
                x.UserName = UserName;
            }).Create();

            _producer = _rabbitClient.GetProducer <Data>(ExchangeName, QueueName, _dataSerializer.ToProto);
        }
Exemple #25
0
 public void Stop()
 {
     client.CloseConnection();
     client = null;
     fingerPrinterManager.Stop();
     fingerPrintThread.Join(1000);
     if (fingerPrintThread.IsAlive)
     {
         fingerPrintThread.Abort();
     }
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="host"></param>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <param name="loger"></param>
        public TracingRecordRabbitmq(string host, string userName, string pwd, ILoger loger = null)
        {
            Raven.Rpc.Tracing.Record.RabbitMQ.Options rabbitMQOptions = new Options();
            rabbitMQOptions.SerializerType = SerializerType.NewtonsoftJson;
            rabbitMQOptions.HostName       = host;
            rabbitMQOptions.UserName       = userName;
            rabbitMQOptions.Password       = pwd;
            rabbitMQOptions.Loger          = loger;

            rabbitMQClient = RabbitMQClient.GetInstance(rabbitMQOptions);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="host"></param>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <param name="loger"></param>
        public TracingRecordRabbitmq(string host, string userName, string pwd, MessageQueue.ILoger loger = null)
        {
            Raven.MessageQueue.WithRabbitMQ.Options rabbitMQOptions = new Options();
            rabbitMQOptions.SerializerType = SerializerType.NewtonsoftJson;
            rabbitMQOptions.HostName = host;
            rabbitMQOptions.UserName = userName;
            rabbitMQOptions.Password = pwd;
            rabbitMQOptions.Loger = loger;

            rabbitMQClient = RabbitMQClient.GetInstance(rabbitMQOptions);
        }
        public async Task UpdateStock_Test()
        {
            // Arrange

            var stockRep = new StockTradingRepository(new AmazonDynamoDBClient());

            var oldStock = new StockDB();

            oldStock.Name        = "SendStockTestUpdate";
            oldStock.Price       = 123.45f;
            oldStock.LastUpdated = System.DateTime.Now.ToString();

            var newStock = new StockDB();

            newStock.Name        = "SendStockTestUpdate";
            newStock.Price       = 678.90f;
            newStock.LastUpdated = System.DateTime.Now.ToString();

            // Act
            await stockRep.AddStock(oldStock);

            var result1 = await stockRep.GetItem(oldStock.Name);

            await stockRep.UpdateStock(newStock);

            var result2 = await stockRep.GetItem(newStock.Name);

            // Assert
            Assert.AreNotEqual(result1.Price, result2.Price);

            // Clean-up
            await stockRep.DeleteStock(newStock);

            // Clean up messages
            // Initiate RabbitMQ
            RabbitMQClient client = new RabbitMQClient("Patch_Queue", "stock.patch");

            ConnectionFactory _factory;
            IConnection       _connection;
            IModel            _model;

            _factory = new ConnectionFactory
            {
                HostName = "localhost",
                UserName = "******",
                Password = "******"
            };

            _connection = _factory.CreateConnection();
            _model      = _connection.CreateModel();
            _model.QueuePurge("Add_Queue");
            _model.QueuePurge("Delete_Queue");
            _model.QueuePurge("Patch_Queue");
        }
Exemple #29
0
        public async Task UpdateStock(StockDB stockDB)
        {
            // create a new queue for each operation

            RabbitMQClient client = new RabbitMQClient("Patch_Queue", "stock.patch");

            client.SendMethod(stockDB, "stock.patch");
            client.Close();

            // update to dynamoDB
            await _context.SaveAsync(stockDB);
        }
Exemple #30
0
        public async Task DeleteStock(StockDB stockDB)
        {
            // create a new queue for each operation

            RabbitMQClient client = new RabbitMQClient("Delete_Queue", "stock.delete");

            client.SendMethod(stockDB, "stock.delete");
            client.Close();

            // delete from dynamoDB
            await _context.DeleteAsync(stockDB);
        }
Exemple #31
0
        public async Task AddStock(StockDB stockDB)
        {
            // create a new queue for each operation

            RabbitMQClient client = new RabbitMQClient("Add_Queue", "stock.add");

            client.SendMethod(stockDB, "stock.add");
            client.Close();

            // save to dynamoDB
            await _context.SaveAsync(stockDB);
        }
Exemple #32
0
        public void TestMethod1()
        {
            MQConfig config = new MQConfig("localhost", "guest", "guest")
            {
                VirtualHost = "/"
            };
            RabbitMQClient client = new RabbitMQClient(config);

            client.Pull <MqModel>((x) =>
            {
                Console.WriteLine(x.ToJson());
            });
        }
        public HttpResponseMessage Post(Message message)
        {
            using (var rabbitMQ = new RabbitMQClient())
            {
                rabbitMQ.Channel.BasicPublish(
                    exchange: "",
                    routingKey: "hello",
                    basicProperties: null,
                    body: SerializeMessage(message));
            }

            return(Request.CreateResponse(HttpStatusCode.Created));
        }
 public RabbitMQClientManager()
 {
     RabbitMQConfig rabbitMQConfig = new RabbitMQConfig("RabbitMQ_RavenLogs");
     rabbitMQOptions = new Raven.MessageQueue.WithRabbitMQ.Options()
     {
         SerializerType = SerializerType.NewtonsoftJson,
         HostName = rabbitMQConfig.hostName,
         Password = rabbitMQConfig.password,
         UserName = rabbitMQConfig.username,
         //MaxQueueCount = 100000,
         Loger = new Loger()
     };
     rabbitMQClient = RabbitMQClient.GetInstance(rabbitMQOptions);
 }
Exemple #35
0
        /// <summary>
        /// 构造器
        /// </summary>
        public RabbitQueueManager()
        {
            ESBConfig esbConfig = m_ESBProxy.RegistryConsumerClient.ESBConfig;


            if (esbConfig != null && esbConfig.MessageQueue.Count > 0)
            {
                //String esbQueue = Config.GetConfig<String>("ESB.Queue");
                String esbQueue = esbConfig.MessageQueue[0].Uri;
                XTrace.WriteLine("读取到ESB队列地址:{0}", esbQueue);

                String[] paramMQ = esbQueue.Split(':');
                m_RabbitMQ = new RabbitMQClient(paramMQ[0], paramMQ[2], paramMQ[3], Int32.Parse(paramMQ[1]));
            }
            else
            {
                String err = "无法获取到有效的队列地址!";
                XTrace.WriteLine(err);
                throw new Exception(err);
            }
        }
        public async Task CreateBatchPublishAndConsume()
        {
            var connectionFactory = CreateConnectionFactory();

            const int messageAmount = 100;

            var messages = GenerateMessages(messageAmount);

            using (var queueClient = new RabbitMQClient(connectionFactory))
            {
                var queueName = $"IntegratedTestQueue_{Guid.NewGuid()}";

                queueClient.EnsureQueueExists(queueName);

                queueClient.BatchPublish("", queueName, messages);

                var receivedMessages = new ConcurrentBag<string>();

                var worker = await SimpleMessageProcessingWorker<string>.CreateAndStartAsync(queueClient, queueName,
                    message => BatchDoSomething(message, receivedMessages), CancellationToken.None);

                const int timeLimit = 10000;

                var elapsedTime = 0;

                while (receivedMessages.Count < messageAmount && elapsedTime < timeLimit)
                {
                    await Task.Delay(100);
                    elapsedTime += 100;
                }

                worker.Stop();

                queueClient.QueueDelete(queueName);

                receivedMessages.Count.ShouldBe(messages.Count);
                receivedMessages.ShouldBeSubsetOf(messages);
            }
        }
        public async Task ConsumerScaling()
        {
            var connectionFactory = CreateConnectionFactory();

            int messageAmount = 30000;

            var messages = GenerateMessages(messageAmount);

            using (var queueClient = new RabbitMQClient(connectionFactory))
            {
                var queueName = $"IntegratedTestQueue_{Guid.NewGuid()}";

                queueClient.EnsureQueueExists(queueName);

                queueClient.BatchPublish("", queueName, messages);

                var worker = await SimpleMessageProcessingWorker<string>.CreateAndStartAsync(queueClient, queueName,
                            async message => await Task.Delay(20), CancellationToken.None, new ConsumerCountManager(4, 50, 1000, 2000));

                const int timeLimit = 1200000;

                var elapsedTime = 0;

                while (elapsedTime < timeLimit)
                {
                    await Task.Delay(100);
                    elapsedTime += 100;

                    if (elapsedTime%1000 == 0 && messageAmount < 70000)
                    {
                        messages = GenerateMessages(1000);
                        queueClient.BatchPublish("", queueName, messages);
                        messageAmount += 1000;
                    }
                }

                worker.Stop();

                queueClient.QueueDelete(queueName);
            }
        }
        public async Task DelayedPublish()
        {
            var connectionFactory = CreateConnectionFactory();

            using (var queueClient = new RabbitMQClient(connectionFactory))
            {
                var queueName = $"IntegratedTestQueue_{Guid.NewGuid()}";

                try
                {
                    queueClient.QueueDeclare(queueName);
                    queueClient.ExchangeDeclare("delayedTargetExchange");
                    queueClient.QueueBind(queueName, "delayedTargetExchange", "delayedTargetRoutingKey");

                    queueClient.DelayedPublish("delayedTargetExchange", "delayedTargetRoutingKey", "delayedMessage",
                        TimeSpan.FromSeconds(5));

                    queueClient.GetMessageCount(queueName).ShouldBe<uint>(0);

                    await Task.Delay(TimeSpan.FromSeconds(5));

                    queueClient.GetMessageCount(queueName).ShouldBe<uint>(1);
                }
                finally
                {
                    queueClient.QueueDelete(queueName);
                }
            }
        }
Exemple #39
0
        /// <summary>
        /// 配置队列线程
        /// </summary>
        private void ConfigQueueThread()
        {
            String appName = m_ConsumerConfig.ApplicationName;

            if (m_EsbConfig.ServiceConfig != null && m_EsbConfig.ServiceConfig.Count > 0)
            {
                //--根据QueueCenter的消费者配置文件中的ApplicationName找到和本机相关的配置文件
                List<EsbView_ServiceConfig> lstServcieConfig = m_EsbConfig.ServiceConfig.FindAll(x =>{
                    return !String.IsNullOrEmpty(x.QueueCenterUri) && appName.EndsWith(x.QueueCenterUri);
                });

                //--删除不应该由本机消费的队列并停用相关线程
                DeleteQueueThread(lstServcieConfig);

                //--添加本机应该消费的队列
                foreach (EsbView_ServiceConfig sc in lstServcieConfig)
                {
                    if (!m_QueueThreadDict.ContainsKey(sc.ServiceName))
                    {
                        RabbitMQClient rabbitMQ = new RabbitMQClient(m_ParamMQ[0], m_ParamMQ[2], m_ParamMQ[3], Int32.Parse(m_ParamMQ[1]));
                        QueueThread qt = new QueueThread(sc.ServiceName, rabbitMQ);
                        qt.Start();

                        m_QueueThreadDict[sc.ServiceName] = qt;
                    }
                }
            }
            else
            {
                //--删除不应该由本机消费的队列并停用相关线程
                DeleteQueueThread(null);
            }
        }