static void Main(string[] args) { var factory = GetConnectionFactory(); using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { DeclareExchange(channel); DeclareQ(channel, Constants.MASTER_CUSTOMER_QUEUE_NAME); SetUpQoS(channel); BindToQ(channel, Constants.MASTER_CUSTOMER_QUEUE_NAME, Constants.NEW_CUSTOMER_EVENT); Console.WriteLine(" [CRM] Waiting for messages."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (Model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var routingKey = ea.RoutingKey; Console.WriteLine(" [>>>>>>>>>>] Received MESSAGE '{0}'", routingKey); ProcessMessage(channel, message, routingKey); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: Constants.MASTER_CUSTOMER_QUEUE_NAME, noAck: false, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } }
private void Connect() { var cf = new ConnectionFactory(); _connection = cf.CreateConnection(); _channel = _connection.CreateModel(); _channel.ExchangeDeclare(_configurationService.WorkersExchange, ExchangeType.Direct); // Listen for heartbeats _channel.QueueDeclare(_configurationService.WorkerPingQueue, false, false, true, null); _channel.QueueBind(_configurationService.WorkerPingQueue, _configurationService.WorkersExchange, _configurationService.WorkerPingQueue); var heartbeatConsumer = new EventingBasicConsumer(_channel); heartbeatConsumer.Received += OnReceivedHeartbeat; heartbeatConsumer.ConsumerCancelled += OnConsumerCancelled; heartbeatConsumer.Shutdown += OnShutdown; _channel.BasicConsume(_configurationService.WorkerPingQueue, true, heartbeatConsumer); // Listen or status changes _channel.QueueDeclare(_configurationService.WorkerStatusQueue, false, false, true, null); _channel.QueueBind(_configurationService.WorkerStatusQueue, _configurationService.WorkersExchange, _configurationService.WorkerStatusQueue); var statusConsumer = new EventingBasicConsumer(_channel); statusConsumer.Received += OnReceivedStatus; statusConsumer.ConsumerCancelled += OnConsumerCancelled; statusConsumer.Shutdown += OnShutdown; _channel.BasicConsume(_configurationService.WorkerStatusQueue, false, statusConsumer); }
public RpcClient() { var factory = new ConnectionFactory() { HostName = "localhost" }; connection = factory.CreateConnection(); channel = connection.CreateModel(); replyQueueName = channel.QueueDeclare().QueueName; consumer = new EventingBasicConsumer(channel); props = channel.CreateBasicProperties(); var correlationId = Guid.NewGuid().ToString(); props.CorrelationId = correlationId; props.ReplyTo = replyQueueName; consumer.Received += (model, ea) => { var body = ea.Body; var response = Encoding.UTF8.GetString(body); if (ea.BasicProperties.CorrelationId == correlationId) { respQueue.Add(response); } }; }
private static void Main(string[] args) { var factory = new ConnectionFactory() { Uri = "amqp://*****:*****@black-boar.rmq.cloudamqp.com/nopqbtng" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "OnAMission", type: "fanout"); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queue: queueName, exchange: "OnAMission", routingKey: ""); Console.WriteLine(" [*] Waiting for logs."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] {0}", message); }; channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } }
public static void Main() { var factory = new ConnectionFactory() { HostName = "localhost" }; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "task_queue", durable: true, exclusive: false, autoDelete: false, arguments: null); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); Console.WriteLine(" [*] Waiting for messages."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); int dots = message.Split('.').Length - 1; Thread.Sleep(dots * 1000); Console.WriteLine(" [x] Done"); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: "task_queue", noAck: false, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } }
public RabbitMqConsumer(Uri uri, string exchange, IEnumerable<string> routingKeys) { var connectionFactory = new ConnectionFactory { Uri = uri.ToString(), }; _connection = connectionFactory.CreateConnection(); _model = _connection.CreateModel(); _model.ExchangeDeclare(exchange, ExchangeType.Topic, false); var queueName = string.Format("test-{0}", Guid.NewGuid()); _model.QueueDeclare( queueName, false, false, true, null); foreach (var routingKey in routingKeys) { _model.QueueBind( queueName, exchange, routingKey, null); } _eventingBasicConsumer = new EventingBasicConsumer(_model); _eventingBasicConsumer.Received += OnReceived; _model.BasicConsume(queueName, false, _eventingBasicConsumer); }
public void TestEventingConsumerRegistrationEvents() { string q = Model.QueueDeclare(); var registeredLatch = new ManualResetEvent(false); object registeredSender = null; var unregisteredLatch = new ManualResetEvent(false); object unregisteredSender = null; EventingBasicConsumer ec = new EventingBasicConsumer(Model); ec.Registered += (s, args) => { registeredSender = s; registeredLatch.Set(); }; ec.Unregistered += (s, args) => { unregisteredSender = s; unregisteredLatch.Set(); }; string tag = Model.BasicConsume(q, false, ec); Wait(registeredLatch); Assert.IsNotNull(registeredSender); Assert.AreEqual(ec, registeredSender); Assert.AreEqual(Model, ((EventingBasicConsumer)registeredSender).Model); Model.BasicCancel(tag); Wait(unregisteredLatch); Assert.IsNotNull(unregisteredSender); Assert.AreEqual(ec, unregisteredSender); Assert.AreEqual(Model, ((EventingBasicConsumer)unregisteredSender).Model); }
public static void HandleQueueItems() { var factory = new ConnectionFactory { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "VehicleQueue", durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); PluginManager.HandleMessageForLoadedPlugins(new ExampleMessage { BodyText = message }); }; channel.BasicConsume(queue: "VehicleQueue", noAck: true, consumer: consumer); Thread.Sleep(new TimeSpan(0, 0, 10)); } }
public static void Receive2() { var factory = new RabbitMQ.Client.ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { var queueDeclare = channel.QueueDeclare("task_queue", true, false, false, null); //用于平衡调度,指定在接收端为处理完成之前不分配其他消息给该接收端 //如果不设置,假如有100条待处理记录,有两个接收端处理,无论两个接收端处理速度快慢,都同等分配50条 //如果设置该平衡调度,处理速度快的客户端会多分配 channel.BasicQos(0, 1, false); var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); channel.BasicAck(ea.DeliveryTag, false); var i = Convert.ToInt32(message.Substring(message.Length - 1, 1)); System.Threading.Thread.Sleep((i % 2 == 1 ? 5 : 1) * 1000); }; channel.BasicConsume(queue: queueDeclare.QueueName, noAck: false, consumer: consumer); Console.WriteLine("consumer启动成功,Press [enter] to exit."); Console.ReadLine(); //注意不要跳出,或者会释放资源,无法自动同步 } } }
public static void Main() { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) {// tutaj tez deklarujemy kolejke, ze wzgledu na to, iż możemy rozpoczac odbnieranie nim wysłannik wyśle wiadomość //chcemy miec pewnośc, że kolejka istnieje channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); //mowimy serwerowi by dostarczył nam wiadomośc z kolejki var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); }; channel.BasicConsume(queue: "hello", noAck: true, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } }
public static void Run() { var factory = new ConnectionFactory() { HostName = "localhost" }; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "logs", type: "fanout"); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queue: queueName, exchange: "logs", routingKey: ""); Console.WriteLine(" [*] Waiting for logs."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] {0}", message); }; string basicConsume = channel.BasicConsume(queue: queueName, noAck: false, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } }
public static void Receive1() { var factory = new RabbitMQ.Client.ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { var queueDeclare = channel.QueueDeclare("hello", false, false, false, null); //平衡调度,在Receiver处理并确认前一个消息之前,不会分发新的消息给Receiver channel.BasicQos(0, 1, false); var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel); consumer.Received += (sender, ea) => { var message = Encoding.UTF8.GetString(ea.Body); Console.WriteLine("[x] Received {0}", message); channel.BasicAck(ea.DeliveryTag, false); }; channel.BasicConsume(queueDeclare.QueueName, false, consumer); Console.WriteLine("consumer启动成功,Press [enter] to exit."); Console.ReadLine(); //注意不要跳出,或者会释放资源,无法自动同步 } } }
public void Worker() { Text log = GameObject.Find("console").GetComponent<Text>(); var factory = new ConnectionFactory() { HostName = "diablo", UserName = "******" ,Password = "******"}; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { //var body = ea.Body; //var message = Encoding.UTF8.GetString(body); //Console.WriteLine(" [x] Received {0}", message); /// int dots = message.Split('.').Length - 1; // Thread.Sleep(1000); log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] recebendo mensagens. \n"; channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: "Work_Queue", noAck: false, consumer: consumer); } }
static void Main(string[] args) { var factory = new ConnectionFactory { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { // Declare the exchange channel.ExchangeDeclare(exchange: "direct_logs", type: ExchangeType.Direct); // Declare anonymous/temporary queue var queueName = channel.QueueDeclare().QueueName; var routingKey = args[0]; // Bind to the exchange channel.QueueBind(queue: queueName, exchange: "direct_logs", routingKey: routingKey); Console.WriteLine("[*] Waiting for logs..."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, dlvrArgs) => { var body = dlvrArgs.Body; var routingKey1 = dlvrArgs.RoutingKey; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0} : {1}", routingKey1, message); }; channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer); Console.ReadLine(); } } }
public override void StartListening() { _rabbitConnection = _configuration.RabbitMqClusterMembers?.Count > 0 ? _configuration.ConnectionFactory.CreateConnection(_configuration.RabbitMqClusterMembers) : _configuration.ConnectionFactory.CreateConnection(); _publishModel = _rabbitConnection.CreateModel(); _receiveModel = _rabbitConnection.CreateModel(); _receiveModel.ExchangeDeclare(_configuration.ExchangeName, ExchangeType.Fanout, true); var queue = _configuration.QueueName == null ? _receiveModel.QueueDeclare() : _receiveModel.QueueDeclare(_configuration.QueueName, true, false, false, new Dictionary<string, object>()); _receiveModel.QueueBind(queue.QueueName, _configuration.ExchangeName, ""); var consumer = new EventingBasicConsumer(_receiveModel); consumer.Received += (sender, args) => { var message = new RabbitMqMessageWrapper { Bytes = args.Body, Id = Convert.ToUInt64(Encoding.UTF8.GetString((byte[]) args.BasicProperties.Headers[MessageIdHeader])) }; OnMessage(message); }; _receiveModel.BasicConsume(queue.QueueName, true, consumer); }
private static void Main(string[] args) { Console.WriteLine("----------Sad Receiver----------"); Console.WriteLine("Press [Enter] to exit."); var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "Emotional_Messages", type: "direct"); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queue: queueName, exchange: "Emotional_Messages", routingKey: "Sad"); Console.WriteLine("Waiting for messages..."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" Received {0}", message); }; channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } }
/// <summary> /// Initializes a new instance of the <see cref="RabbitMqEventConsumer"/> class. /// </summary> /// <param name="connectionFactory">The connection factory.</param> /// <param name="exchangePath">The exchange path.</param> /// <param name="queue">The queue.</param> public RabbitMqEventConsumer(ConnectionFactory connectionFactory, string exchangePath, string queue) { _active = 1; _connection = connectionFactory.CreateConnection(); _model = _connection.CreateModel(); _queue = _model.QueueDeclare(queue, true, false, false, new Hashtable()); // bind the queue to an exchange if specified if (exchangePath != null) { _model.QueueBind(_queue, exchangePath, string.Empty); } EventingBasicConsumer eventingBasicConsumer = new EventingBasicConsumer(); eventingBasicConsumer.Received += HandleEvent; _model.BasicConsume(_queue, true, eventingBasicConsumer); #if false _subscription = new Subscription(_model, _queue, true); var thread = new Thread(ReceiveEvents); thread.IsBackground = true; thread.Name = "rabbitmq:consumer"; thread.Start(); #endif var uriBuilder = new UriBuilder( "rabbitmq", connectionFactory.HostName, connectionFactory.Port, queue); Uri = uriBuilder.Uri; }
public Consumer(string queueName, IDictionary<string, string> headers, bool matchAll = true) { var factory = new ConnectionFactory {HostName = "localhost"}; _connection = factory.CreateConnection(); _channel = _connection.CreateModel(); var args = new Dictionary<String, Object>(); if (headers != null) { args.Add("x-match", matchAll ? "all" : "any"); foreach (var item in headers) { args.Add(item.Key, item.Value); } } _channel.ExchangeDeclare(ExchangeName, "headers", true); _channel.QueueDeclare(queueName, true, false, false, args); _channel.QueueBind(queueName, ExchangeName, string.Empty); const bool nonTransactional = true; _consumer = new EventingBasicConsumer(); _consumer.Received += ConsumerReceived; _channel.BasicConsume(queueName, nonTransactional, _consumer); }
public Rabbit(string address) { cf = new ConnectionFactory(); //cf.Port = 35672; cf.UserName = "******"; cf.Password = "******"; cf.Address = address; conn = cf.CreateConnection(); IModel c = Connect(); conn.AutoClose = false; UriSettings(); _address = address.Substring(0, address.IndexOf(":")); ProcessQueues(); System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.Interval = 60 * 1000; aTimer.Enabled = true; var consumer = new EventingBasicConsumer(); consumer.Received += (model, ea) => { ProcessQueues(); Console.WriteLine("Received event"); }; c.BasicConsume("task_queue", false, null, consumer); Console.ReadKey(); }
public void TestEventingConsumerRegistrationEvents() { string q = Model.QueueDeclare(); bool registeredInvoked = false; object registeredSender = null; bool unregisteredInvoked = false; object unregisteredSender = null; EventingBasicConsumer ec = new EventingBasicConsumer(Model); ec.Registered += (s, args) => { registeredInvoked = true; registeredSender = s; }; ec.Unregistered += (s, args) => { unregisteredInvoked = true; unregisteredSender = s; }; string tag = Model.BasicConsume(q, false, ec); Assert.IsTrue(registeredInvoked); Assert.IsNotNull(registeredSender); Assert.AreEqual(ec, registeredSender); Assert.AreEqual(Model, ((EventingBasicConsumer)registeredSender).Model); Model.BasicCancel(tag); Assert.IsTrue(unregisteredInvoked); Assert.IsNotNull(unregisteredSender); Assert.AreEqual(ec, unregisteredSender); Assert.AreEqual(Model, ((EventingBasicConsumer)unregisteredSender).Model); }
static void Main(string[] args) { var channel = _connection.CreateModel(); channel.QueueDeclare("BanksList", true, false, false, null); var consumer = new EventingBasicConsumer(); consumer.Model = channel; consumer.Received += (s, e) => { var message = e.Body.ToRequestMessage<BanksListMessage>(); foreach (var bankName in message.BanksList) { var bankChannelName = ConfigurationManager.AppSettings[bankName].ToString(); _channels[bankChannelName].BasicPublish("", bankChannelName, null, message.ToByteArray()); } }; channel.BasicConsume("BanksList", true, consumer); }
static void Main(string[] args) { var factory = GetConnectionFactory(); using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { DeclareExchange(channel); DeclareQ(channel, Constants.LOGGING_QUEUE_NAME); SetUpQoS(channel); foreach (var eventName in Constants.EventCollection) { BindToQ(channel, Constants.LOGGING_QUEUE_NAME, eventName); } Console.WriteLine(" [LOGGER] Waiting for messages."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var routingKey = ea.RoutingKey; LogMessage(routingKey, message); Console.WriteLine(" [x] Received '{0}':'{1}'", routingKey, message); //channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: Constants.LOGGING_QUEUE_NAME, noAck: true, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } }
private static void Main(string[] args) { Console.WriteLine("----------Receiver (ALL HAPPY MESSAGES)----------"); Console.WriteLine("Press [Enter] to exit."); var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "topic_example", type: "topic"); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queue: queueName, exchange: "topic_example", routingKey: "Happy.*"); Console.WriteLine("Waiting for messages..."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var routingKey = ea.RoutingKey; Console.WriteLine(" Received '{0}':'{1}'", routingKey, message); }; channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer); Console.ReadLine(); } }
public static void Main() { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(ExchangeName, ExchangeType); //non-durable, exclusive, autodelete queue with a generated name var anonymousQueueName = channel.QueueDeclare().QueueName; Console.WriteLine("anonymousQueueName is:" + anonymousQueueName); //Create a binding - makes the exchange filter to the queue channel.QueueBind(anonymousQueueName, ExchangeName, EmptyRoutingKey); Console.WriteLine(" [*] Waiting for logs."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] {0}", message); }; channel.BasicConsume(anonymousQueueName, true, consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } }
public void Subscribe(string queueName, EventHandler<BasicDeliverEventArgs> handler) { CreateQueue(queueName); var consumer = new EventingBasicConsumer(_model); consumer.Received += handler; _model.BasicConsume(queueName, true, consumer); }
private static void HelloWorld() { var connectionFactory = new ConnectionFactory { HostName = "localhost" }; using (var connection = connectionFactory.CreateConnection()) { using (IModel channel = connection.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, eventArgs) => { string body = Encoding.UTF8.GetString(eventArgs.Body); Console.WriteLine(" [x] Received {0}", body); }; channel.BasicConsume("hello", true, consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } }
public override void StartListening() { _rabbitConnection = Configuration.ConnectionFactory.CreateConnection(); _publishModel = _rabbitConnection.CreateModel(); _subscribeModel = _rabbitConnection.CreateModel(); _publishModel.ExchangeDeclare(Configuration.StampExchangeName, "x-stamp", durable: true); _subscribeModel.ExchangeDeclare(Configuration.ExchangeName, ExchangeType.Fanout, durable: true); _subscribeModel.QueueDeclare(Configuration.QueueName, durable: false, exclusive: false, autoDelete: true, arguments: new Dictionary<string, object>()); _subscribeModel.QueueBind(Configuration.QueueName, Configuration.ExchangeName, ""); var consumer = new EventingBasicConsumer(_subscribeModel); consumer.Received += (sender, args) => { try { OnMessage(new RabbitMqMessageWrapper { Bytes = args.Body, Id = Convert.ToUInt64(args.BasicProperties.Headers["stamp"]) }); } finally { _subscribeModel.BasicAck(args.DeliveryTag, multiple: false); } }; _subscribeModel.BasicConsume(Configuration.QueueName, noAck: false, consumer: consumer); }
protected virtual void OnTick(object sender, ElapsedEventArgs e) { var connectionFactory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = connectionFactory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.ExchangeDeclare("TestWindowsExchange", "fanout"); channel.QueueDeclare("TestWindowsQueue", true, false, false, null); channel.QueueBind("TestWindowsQueue", "TestWindowsExchange", ""); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); Console.WriteLine(" [*] Waiting for messages"); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); CallSubscriberApi(message); Console.WriteLine(" [x] Done"); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: "TestWindowsQueue", noAck: false, consumer: consumer); Console.WriteLine("Press Enter to exit"); Console.ReadLine(); } } }
private static void ReceiveMessages() { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "Hello Queue", durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); }; channel.BasicConsume(queue: "Hello Queue", noAck: true, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } }
public void receivePSMessage() { Debug.Log("Start"); Text log = GameObject.Find("console").GetComponent<Text>(); log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Aguardando mensagens.\n"; var factory = new ConnectionFactory() { HostName = "diablo", UserName = "******", Password = "******" }; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { if(uuid == ""){ setUuid("amq-" + Guid.NewGuid().ToString()); } channel.ExchangeDeclare(exchange: "publishSubEX", type: "fanout"); var queueName = channel.QueueDeclare(uuid, false,false,false,null); channel.QueueBind(queueName,"publishSubEX",""); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; Utils.SaveFileToDisk("rabbit.png",body); var fileInfo = new System.IO.FileInfo("rabbit.png"); var fileSize = (fileInfo.Length/1024f)/1024f; log.text = log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Mensagem Enviada Publish / Subscribe : " + fileSize.ToString("0.00") + " MB" + "\n"; }; channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer); } }
public RabbitMQReceiver(IConnection connection, string queueName) { Connection = connection; QueueName = queueName; MessageStringProperties = null; consumer = new EventingBasicConsumer(); IsStarted = false; }
// Usando filtrando por error: // RabbitMQ.Consumer.exe error private static void ConsumoEnvioComExchange_Direct(string[] args) { // Instalando RabbitMQ no projeto // Install-Package RabbitMQ.Client // Host a se conectar var factory = new ConnectionFactory() { HostName = "localhost" }; // Cria uma conexão específica para o endpoint using (var connection = factory.CreateConnection()) { // Abre um canal e cria a fila using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "direct_logs", type: "direct"); // Quando criamos uma fila sem parâmentros usando QueueDeclare() // É criada uma fila não durável, exclusiva e autoDelete com um nome gerado automáticamente // Ex: // amq.gen-JzTY20BRgKO-HjmUJj0wLg var queueName = channel.QueueDeclare().QueueName; if (args.Length < 1) { Console.Error.WriteLine("Usage: {0} [info] [warning] [error]", Environment.GetCommandLineArgs()[0]); Console.WriteLine("Press [enter] to exit."); Console.ReadLine(); Environment.ExitCode = 1; return; } foreach (var severity in args) { channel.QueueBind(queue: queueName, exchange: "direct_logs", routingKey: severity); } Console.WriteLine("[*] Aguardando por mensagens.."); // Cria um consumer básico var consumer = new EventingBasicConsumer(channel); // Cria um evento que será disparado quando tiver algum item para ser recebidos consumer.Received += (model, routingkey) => { var body = routingkey.Body; // Pega a mensagem pela rota var message = Encoding.UTF8.GetString(body); // Converte os bytes em string Console.WriteLine("[x] Mensagem recebida: {0}", message); }; channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer); Console.WriteLine("Press [enter] to exit."); Console.ReadLine(); } } }
public static void Receive6() { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "rpc_queue", durable: false, exclusive: false, autoDelete: false, arguments: null); channel.BasicQos(0, 1, false); var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel); channel.BasicConsume(queue: "rpc_queue", noAck: false, consumer: consumer); Console.WriteLine(" [x] Awaiting RPC requests"); consumer.Received += (model, ea) => { string response = null; var body = ea.Body; var props = ea.BasicProperties; var replyProps = channel.CreateBasicProperties(); replyProps.CorrelationId = props.CorrelationId; try { var message = Encoding.UTF8.GetString(body); int n = int.Parse(message); Console.WriteLine(" [.] fib({0})", message); response = "返回" + message; } catch (Exception e) { Console.WriteLine(" [.] " + e.Message); response = ""; } finally { var responseBytes = Encoding.UTF8.GetBytes(response); channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, basicProperties: replyProps, body: responseBytes); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); } }; Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } }
/// <summary> /// rabbitmq测试 /// </summary> public static void RabbitTest() { Task t = new Task(() => { var factory = new ConnectionFactory { HostName = "localhost", UserName = "******", Password = "******", Port = 5672, VirtualHost = "/", AutomaticRecoveryEnabled = true }; //创建消息队列连接 var connection = factory.CreateConnection(); IModel channel = connection.CreateModel(); //绑定交换机 channel.ExchangeDeclare("lijie_Exchange", "direct", true, false); //申明消息队列 channel.QueueDeclare("jietest0304", true, false, false); //绑定消息队列到交换机 channel.QueueBind("jietest0304", "lijie_Exchange", "Key_jietest0304"); //费者在接收到队列里的消息但没有返回确认结果之前,队列不会将新的消息分发给该消费者。队列中没有被消费的消息不会被删除,还是存在于队列中 channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); EventingBasicConsumer consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel); //消费事件 consumer.Received += (p, q) => { ReadOnlyMemory <byte> body = q.Body; var message = System.Text.Encoding.UTF8.GetString(body.ToArray()); Console.WriteLine($"消费:{message}"); //消息确认 channel.BasicAck(deliveryTag: q.DeliveryTag, multiple: false); }; //启动消费 channel.BasicConsume("jietest0304", autoAck: false, consumer: consumer); }); t.Start(); while (true) { } }
/// <summary> /// //发消息对队列,通过Rpc事件驱动获取回复消息(推荐此方式) /// /// </summary> /// <param name="count"></param> private void InsertAndGetResponseMsgByEnevt(int count) { #region ConnectionFactory var factory = new ConnectionFactory(); factory.HostName = "192.168.1.69"; //RabbitMQ服务在本地运行 factory.UserName = "******"; //用户名 factory.Password = "******"; //密码 factory.VirtualHost = "newbpo"; #endregion /* * 发布消息,消息找队列,常用3种路由方式: * Direct:根据路由键进行,消息发送到该交换机且绑定有该路由键的队列; * Fanout:广播模式,忽略路由键,消息会发送到绑定在交换机上面的所有队列; * Topic:类似Direct,但是匹配路由键可以根据匹配符进行匹配队列; */ using (var conn = factory.CreateConnection()) //创建连接 { using (IModel channel = conn.CreateModel()) //创建对象 { //声明队列 channel.QueueDeclare(queue: "OrderOnly", durable: true, exclusive: false, autoDelete: false, arguments: null); channel.QueueDeclare(queue: "OrderOnly2", durable: true, exclusive: false, autoDelete: false, arguments: null); //声明交换机 channel.ExchangeDeclare(exchange: "OrderOnlyChange", type: ExchangeType.Direct, durable: true, autoDelete: false, arguments: null); //队列绑定到交换机,路由Key:OrderOnlyKey channel.QueueBind(queue: "OrderOnly", exchange: "OrderOnlyChange", routingKey: "OrderOnlyKey", arguments: null); //绑定到交换机,路由Key:OrderOnlyKey2 channel.QueueBind(queue: "OrderOnly2", exchange: "OrderOnlyChange", routingKey: "OrderOnlyKey2", arguments: null); /*重要!!! * 绑定到交换机时可以绑多个routingKey,这样一个队列就会有多个的routeKey, * 发消息是要匹配到任意一个key就会发送到该队列*/ //如下:给OrderOnly2队列又绑了一个OrderOnlyKey3的key //channel.QueueBind(queue: "OrderOnly2", // exchange: "OrderOnlyChange", // routingKey: "OrderOnlyKey3", arguments: null); Console.WriteLine("准备就绪,开始写入~~~"); #region 设置Rpc回复队列,定义消费者接受消息 string replyQueueName = "ReplyQueue"; //声明接受消息回复队列 channel.QueueDeclare(queue: replyQueueName, durable: true, exclusive: false, autoDelete: false, null); //注意:回复的队列不能绑定到交换机,因为如果绑定了,发送的时候交换机会把消息也发送到这个队列,这样消息会造成混乱 //channel.QueueBind(queue: replyQueueName, // exchange: "OrderOnlyChange", // routingKey: string.Empty, arguments: null); Dictionary <string, TaskCompletionSource <string> > resultDic = new Dictionary <string, TaskCompletionSource <string> >(); var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel); consumer.Received += (model, ea) => { //每一次请求的唯一标识 string corrId = ea.BasicProperties.CorrelationId; if (resultDic.Keys.Contains(corrId))//如果包含这个corrId,则把结果赋值给对应的TaskCompletionSource { var body = ea.Body; var message = Encoding.UTF8.GetString(body); //把结果放入到结果集合中 resultDic[corrId].SetResult(message); //Console.WriteLine($"接收到回复消息:{message}"); } }; //处理消息 channel.BasicConsume(queue: replyQueueName, autoAck: true, consumer: consumer); #endregion for (int i = 0; i < count; i++) { string message = $"Task{i}"; byte[] body = Encoding.UTF8.GetBytes(message); //设置回复队列参数 var corrId = Guid.NewGuid().ToString(); var props = channel.CreateBasicProperties(); props.ReplyTo = replyQueueName; //你处理完过后把结果返回到这个队列中。 props.CorrelationId = corrId; //这是我的请求标识 //channel.BasicPublish(exchange: "OrderOnlyChange", // routingKey: string.Empty, // basicProperties: null, // body: body); //利用TaskCompletionSource的特性,异步获取消息时会等待 var result = new TaskCompletionSource <string>(); resultDic.Add(corrId, result); //因为发送时指定路由key为OrderOnlyKey2,所以消息只会推送到OrderOnly2队列 channel.BasicPublish(exchange: "OrderOnlyChange", routingKey: "OrderOnlyKey2", basicProperties: props, //加上basicProperties参数,绑定回复队列 body: body); Console.WriteLine($"消息:{message} 已发送,corrId={corrId}"); Console.WriteLine($"接收到回复消息:{result.Task.Result}"); } } } }
/// <summary> /// RabbitMQ接受消息 /// </summary> /// <param name="queuqname"></param> /// <param name="limitnum">具体入队的队列名称</param> public static void ReceiveMsg(string queuqname, ushort limitnum = 3) { #region 处理方法 try { #region 构建消息队列 //1.实例化连接工厂 var factory = new RabbitMQ.Client.ConnectionFactory(); factory.HostName = RabbitMQ_Host; factory.UserName = RabbitMQ_User; factory.Password = RabbitMQ_Pwd; factory.AutomaticRecoveryEnabled = true; //2. 建立连接 var connection = factory.CreateConnection(); //3. 创建信道 var channel = connection.CreateModel(); var queue_name = queuqname; //项目下游上传的队列信息 bool durable = true; //队列是否持久化 bool exclusive = false; bool autoDelete = false; //设置 autoDeleted=true 的队列,当没有消费者之后,队列会自动被删除 //4. 申明队列 channel.QueueDeclare(queue_name, durable, exclusive, autoDelete, null); //5. 构造消费者实例 var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel); bool autoAck = false; //autoAck:true;自动进行消息确认,当消费端接收到消息后,就自动发送ack信号,不管消息是否正确处理完毕 //autoAck:false;关闭自动消息确认,通过调用BasicAck方法手动进行消息确认 //6. 绑定消息接收后的事件委托 //8. 启动消费者 //设置prefetchCount : 3 来告知RabbitMQ,在未收到消费端的N条消息确认时,不再分发消息,也就确保了当消费端处于忙碌状态时 channel.BasicQos(0, limitnum, false); channel.BasicConsume(queue_name, autoAck, consumer); #endregion #region 队列-接收消息的处理方法 //以这种形式传递方法 //consumer.Received += (model, ea) => { Methed(model, ea, channel);}; consumer.Received += (model, ea) => { try { //var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(ea.Body.ToArray()); //获取消息后进行操作,do something bool flag = false; if (!string.IsNullOrEmpty(message)) { try { //做其他存储或处理操作 } catch (Exception ex) { // //pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-处理Message数据时,发生异常----" + ex.Message); // //pub.ConnError_TestSysShow("RabbitMq-RST", "Item-Attence", "项目下游请求数据-处理Message数据时,发生异常原数据message=" + message); } } else { flag = true; } if (flag) { //操作完毕,则手动确认消息可删除 // 7. 发送消息确认信号(手动消息确认) channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); } } catch (Exception ex) { //JMB_ServiceClass.Common.pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-接收数据后-发生异常:" + ex.Message); } }; #endregion //JMB_ServiceClass.Common.pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-RabbitMQ监听消息启动成功"); } catch (Exception ex) { //JMB_ServiceClass.Common.pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-构建rabbitmq的queue异常:" + ex.Message); //RabbitMQ_Event1_IsRuning = false; //RabbitMQ_Event1_checkDate = DateTime.Now; //JMB_ServiceClass.Common.pub.ConnError("RabbitMQ", "Event_RabbitMQ_Method1", "项目下游请求数据-RabbitMQ监听消息——已关闭"); } //finally //{ // connection.Close();//不能关,关了就停止接收消息了 // channel.Close(); //} #endregion }
static void Main(string[] args) { string type = Console.ReadLine(); //factory.HostName = "10.16.21.19"; switch (type) { case "1": #region 发布消息 var factory = new RabbitMQ.Client.ConnectionFactory(); factory.UserName = "******"; factory.Password = "******"; factory.Port = 5672; factory.HostName = "47.101.160.52"; do { using (var connect = factory.CreateConnection()) { using (var model = connect.CreateModel()) { model.ExchangeDeclare("HistroyCity", "direct", true); var q = model.QueueDeclare("CitiesQueue", true, false, false, null); model.QueueBind("CitiesQueue", "HistroyCity", "CityPublished"); using (var cityTable = new HistoryAirDataEntities()) { int count = (int)(q.MessageCount); if (20 - count > 0) { var list = (from c in cityTable.publish where c.ispublished == false select c).Take(20 - count).ToArray(); if (list.Length == 0) { break; } foreach (var c in list) { var pm = new PublishMessage() { Name = c.name, Url = c.homeurl, PublishIndex = c.index, DataTime = c.datatime }; var message = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(pm)); Console.WriteLine(pm.Name); model.BasicPublish("HistroyCity", "CityPublished", null, message); var pC = cityTable.publish.First(r => r.index == c.index); pC.ispublished = true; } cityTable.SaveChanges(); } } } } Console.WriteLine("*****************"); Thread.Sleep(1200000); } while (true); #endregion break; case "2": #region 更新起始时间,无效的功能 var factory1 = new RabbitMQ.Client.ConnectionFactory(); factory1.UserName = "******"; factory1.Password = "******"; factory1.Port = 5672; factory1.HostName = "47.101.160.52"; using (var connect = factory1.CreateConnection()) { using (var model = connect.CreateModel()) { model.ExchangeDeclare("HistroyCity", "direct", true); var q = model.QueueDeclare("CitiesQueue", true, false, false, null); var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(model); model.BasicQos(0, 1, false); consumer.Received += (channel, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var p = JsonConvert.DeserializeObject <cities>(message); Thread.Sleep(new Random().Next(4000, 10000)); using (var entry = new HistoryAirDataEntities()) using (var seleminun = new ChromeDriver()) //using (var seleminun = new PhantomJSDriver()) { seleminun.Navigate().GoToUrl(p.homeurl); Thread.Sleep(new Random().Next(1000, 2000)); //获取起始时间 var times = seleminun.FindElements(By.XPath("//ul[@class=\"unstyled1\"]/li/a")); string timeT = null; if (times != null & times.Count > 0) { string[] t = times[0].GetAttribute("href").Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); timeT = t.Last(); } //获取当前页码上的信息并写入记录 var rowEs = seleminun.FindElements(By.XPath("//div[@class=\"row\"]/div/table/tbody/tr")); Console.WriteLine(rowEs.Count); //string path = string.Format("{0}\\{1}", Environment.CurrentDirectory, "data"); //using (var sw = new StreamWriter(string.Format("{0}//{1}", path, p.name), true)) { for (int rowIndex = 1; rowIndex < rowEs.Count; rowIndex++) { var trEs = rowEs[rowIndex].FindElements(By.XPath(".//td")); var tempdata = new data() { name = p.name }; tempdata.date = DateTime.Parse(trEs[0].Text); tempdata.aqi = trEs[1].Text; tempdata.rank = trEs[2].Text; int off = 0; if (trEs.Count == 10) { off = 1; tempdata.range = trEs[3].Text; } int p25, p10, so2, no2, O3_8h; float co; if (int.TryParse(trEs[3 + off].Text, out p25)) { tempdata.pm2d5 = p25; } if (int.TryParse(trEs[4 + off].Text, out p10)) { tempdata.pm10 = p10; } if (int.TryParse(trEs[5 + off].Text, out so2)) { tempdata.so2 = so2; } if (float.TryParse(trEs[6 + off].Text, out co)) { tempdata.co = co; } if (int.TryParse(trEs[7 + off].Text, out no2)) { tempdata.no2 = no2; } if (int.TryParse(trEs[8 + off].Text, out O3_8h)) { tempdata.o3_8 = O3_8h; } tempdata.updatetime = DateTime.Now; entry.data.Add(tempdata); //var tempData = new Data() //{ // Date = trEs[0].Text, // AQI = trEs[1].Text, // Rank = trEs[2 + off].Text, // Pm2d5 = trEs[3 + off].Text, // Pm10 = trEs[4 + off].Text, // So2 = trEs[5 + off].Text, // Co = trEs[6 + off].Text, // No2 = trEs[7 + off].Text, // O3_8h = trEs[8 + off].Text //}; //if (trEs.Count == 10) //{ // tempData.Range = trEs[3].Text; //} //sw.WriteLine(JsonConvert.SerializeObject(tempData)); } var target = entry.cities.First(rr => rr.name == p.name); target.starttime = timeT; target.updatetime = DateTime.Now; Console.WriteLine("************"); Console.WriteLine(target.name); Console.WriteLine("************"); } entry.SaveChanges(); } Thread.Sleep(1000); model.BasicAck(ea.DeliveryTag, false); }; model.BasicConsume("CitiesQueue", false, consumer); var r = Console.ReadLine(); if (r.ToLower().Trim() == "over") { return; } } } #endregion break; case "3": #region 获取任务消息并进行数据获取 var factory2 = new RabbitMQ.Client.ConnectionFactory() { UserName = "******", Password = "******", Port = 5672, HostName = "47.101.160.52" }; using (var connect = factory2.CreateConnection()) { using (var model = connect.CreateModel()) { model.ExchangeDeclare("HistroyCity", "direct", true); var q = model.QueueDeclare("CitiesQueue", true, false, false, null); var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(model); model.BasicQos(0, 1, false); consumer.Received += (channel, ea) => { List <data> tempData = null; try { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var p = JsonConvert.DeserializeObject <PublishMessage>(message); tempData = DataManager.GetHistroyData(p); if (tempData != null) { using (var enerty = new HistoryAirDataEntities()) using (var trans = enerty.Database.BeginTransaction()) { for (int i = 0; i < tempData.Count; i++) { enerty.data.Add(tempData[i]); } var reslut = enerty.SaveChanges(); if (reslut > 0) { trans.Commit(); } else { trans.Rollback(); } model.BasicAck(ea.DeliveryTag, false); } } else { model.BasicNack(ea.DeliveryTag, false, true); } } catch (Exception err) { Console.WriteLine(err.Message); Console.WriteLine(err.StackTrace); model.BasicNack(ea.DeliveryTag, false, true); } #region old //using (var entry = new HistoryAirDataEntities()) ////using (var seleminun = new ChromeDriver()) //using (var seleminun = new PhantomJSDriver()) //{ // Thread.Sleep(new Random().Next(240000, 600000)); // string t = HttpUtility.UrlDecode(string.Format("{0}{1}", p.DataTime.Value.Year, p.DataTime.Value.Month.ToString("00"))); // string url = string.Format("{0}&month={1}", p.Url.Trim(), t); // seleminun.Navigate().GoToUrl(url); // Thread.Sleep(new Random().Next(1000, 2000)); // var rowEs = seleminun.FindElements(By.XPath("//div[@class=\"row\"]/div/table/tbody/tr")); // Console.WriteLine(rowEs.Count); // string path = string.Format("{0}\\{1}", Environment.CurrentDirectory, "data"); // using (var sw = new StreamWriter(string.Format("{0}//{1}", path, p.Name), true)) // { // for (int rowIndex = 1; rowIndex < rowEs.Count; rowIndex++) // { // var trEs = rowEs[rowIndex].FindElements(By.XPath(".//td")); // var tempdata = new data() { name = p.Name }; // tempdata.date = DateTime.Parse(trEs[0].Text); // tempdata.aqi = trEs[1].Text; // tempdata.rank = trEs[2].Text; // int p25, p10, so2, co, no2, O3_8h; // if (int.TryParse(trEs[3].Text, out p25)) // { // tempdata.pm2d5 = p25; // } // if (int.TryParse(trEs[4].Text, out p10)) // { // tempdata.pm10 = p10; // } // if (int.TryParse(trEs[5].Text, out so2)) // { // tempdata.so2 = so2; // } // if (int.TryParse(trEs[6].Text, out co)) // { // tempdata.co = co; // } // if (int.TryParse(trEs[7].Text, out no2)) // { // tempdata.no2 = no2; // } // if (int.TryParse(trEs[8].Text, out O3_8h)) // { // tempdata.no2 = no2; // } // entry.data.Add(tempdata); // var tempData = new Data() // { // Date = trEs[0].Text, // AQI = trEs[1].Text, // Rank = trEs[2].Text, // Pm2d5 = trEs[3].Text, // Pm10 = trEs[4].Text, // So2 = trEs[5].Text, // Co = trEs[6].Text, // No2 = trEs[7].Text, // O3_8h = trEs[8].Text // }; // sw.WriteLine(JsonConvert.SerializeObject(tempData)); // } // } // entry.SaveChanges(); //} #endregion }; model.BasicConsume("CitiesQueue", false, consumer); var r = Console.ReadLine(); if (r.ToLower().Trim() == "over") { return; } } } #endregion break; case "4": #region 在数据库中插入任务计划 using (var cityTable = new HistoryAirDataEntities()) { var list = (from c in cityTable.cities select c).ToArray(); for (int yIndex = 2018; yIndex < 2019; yIndex++) { for (int mIndex = 11; mIndex < 12; mIndex++) { foreach (var c in list) { if (yIndex == 2013) { mIndex = 11; } else if (yIndex == DateTime.Now.Year) { if (mIndex + 1 >= DateTime.Now.Month) { continue; } } var p = new publish(); p.name = c.name; p.homeurl = c.homeurl; p.datatime = new DateTime(yIndex, mIndex + 1, 1); cityTable.publish.Add(p); } } } cityTable.SaveChanges(); Console.WriteLine(cityTable.publish.Count()); Console.WriteLine("*****************"); } Console.WriteLine("*****************"); #endregion break; default: break; } #region 获取城市列表并序列化为本地文件 //var selHome = new ChromeDriver(); //selHome.Navigate().GoToUrl("https://www.aqistudy.cn/historydata/"); //var liEs = selHome.FindElements(By.XPath("//ul[@class=\"unstyled\"]/div/li/a")); //List<HistoryCity> cities = new List<HistoryCity>(); //foreach (var item in liEs) //{ // var tempc = new HistoryCity(); // tempc.Name = item.Text.Trim(); // tempc.Url = item.GetAttribute("href"); // cities.Add(tempc); //} //selHome.Close(); //foreach (var item in cities) //{ // using (var sw = new StreamWriter(string.Format("{0}\\{1}", path,item.Name))) // { // sw.Write(JsonConvert.SerializeObject(item)); // } //} #endregion #region 将本地文件写入到数据库中 //List<HistoryCity> cities = new List<HistoryCity>(); //string path = string.Format("{0}\\{1}", Environment.CurrentDirectory, "HistroyCities"); //string[] files = Directory.GetFiles(path); //foreach (var item in files) //{ // using (var sr=new StreamReader(item)) // { // var tempStr = sr.ReadToEnd(); // HistoryCity tempCity = JsonConvert.DeserializeObject<HistoryCity>(tempStr); // cities.Add(tempCity); // } //} //if (!Directory.Exists(path)) //{ // Directory.CreateDirectory(path); //} //try //{ // using (var citiesEnty = new HistoryAirDataEntities()) // { // int count = 0; // foreach (var item in cities) // { // var tempcities = new cities(); // tempcities.name = item.Name; // tempcities.homeurl = item.Url; // citiesEnty.cities.Add(tempcities); // count++; // if (count >= 10) // { // // citiesEnty.SaveChanges(); // count = 0; // } // } // citiesEnty.SaveChanges(); // } //} //catch (Exception err) //{ // Console.Write(err.Message); //} #endregion #region 获取城市历史数据 //string path = Environment.CurrentDirectory + "//Data"; //if (!Directory.Exists(path)) //{ // Directory.CreateDirectory(path); //} //using (var seleminun = new ChromeDriver()) //{ // seleminun.Navigate().GoToUrl("https://www.aqistudy.cn/historydata/daydata.php?city=%E5%AE%89%E9%98%B3&month=201703"); // Thread.Sleep(new Random().Next(1000, 2000)); // var rowEs = seleminun.FindElements(By.XPath("//div[@class=\"row\"]/div/table/tbody/tr")); // Console.WriteLine(rowEs.Count); // List<Data> datalist = new List<Data>(); // for (int rowIndex = 1; rowIndex < rowEs.Count; rowIndex++) // { // var trEs = rowEs[rowIndex].FindElements(By.XPath(".//td")); // var tempData = new Data() // { // Date =DateTime.Parse(trEs[0].Text), // AQI = trEs[1].Text, // Rank = trEs[2].Text, // Pm2d5 = trEs[3].Text, // Pm10 = trEs[4].Text, // So2 = trEs[5].Text, // Co = trEs[6].Text, // No2 = trEs[7].Text, // O3_8h = trEs[8].Text // }; // datalist.Add(tempData); // } // using (var sw=new StreamWriter(string.Format("{0}/{1}",path,"datalist"))) // { // sw.Write(JsonConvert.SerializeObject(datalist)); // } // //var tds = rowEs[rowEs.Count - 1].FindElements(By.XPath(".//td")); // //for (int i = 0; i < tds.Count; i++) // //{ // // Console.WriteLine(tds[i].Text); // //} // Console.ReadLine(); //} #endregion #region 更新起始时间(未完成) //List<HistoryCity> cities = new List<HistoryCity>(); //string path = string.Format("{0}\\{1}", Environment.CurrentDirectory, "HistroyCities"); //string[] files = Directory.GetFiles(path); //foreach (var item in files) //{ // using (var sr = new StreamReader(item)) // { // var tempStr = sr.ReadToEnd(); // HistoryCity tempCity = JsonConvert.DeserializeObject<HistoryCity>(tempStr); // cities.Add(tempCity); // } //} //using (var cityTable=new HistoryAirDataEntities()) //{ // for (int i = 0; i < cities.Count; i++) // { // var city = (from c in cityTable.cities where c.name == cities[i].Name & c.startTime==null select c).ToArray(); // if (city.Length==1) // { // using (var selenum=new ChromeDriver()) // { // selenum.Navigate().GoToUrl(city[0].homeurl); // if (true) // { // } // } // city[0].startTime = null; // } // } //} #endregion }
static void Main(string[] args) { Console.WriteLine("1 发布任务消息;2 将查询结果放入消息队列;3 获取队列中的数据将其放入数据库;4 生产任务计划"); string type = Console.ReadLine(); Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //设置计算引擎json记录路径 //factory.HostName = "10.16.21.19"; switch (type) { case "1": #region 发布任务消息 var factory = new RabbitMQ.Client.ConnectionFactory(); factory.UserName = "******"; factory.Password = "******"; factory.Port = 5672; factory.HostName = "47.101.160.52"; do { using (var connect = factory.CreateConnection()) { using (var model = connect.CreateModel()) { model.ExchangeDeclare("HistroyCity", "direct", true); var q = model.QueueDeclare("CitiesQueue", true, false, false, null); model.QueueBind("CitiesQueue", "HistroyCity", "CityPublished"); using (var cityTable = new HistoryDataEntities()) { int count = (int)(q.MessageCount); if (50 - count > 0) { try { var list = (from c in cityTable.publish where c.ispublished == false select c).OrderByDescending(r => r.datatime).Take(50 - count).ToArray(); if (list.Length == 0) { break; } foreach (var c in list) { var pm = new PublishMessage() { Name = c.name, Url = c.homeurl, PublishIndex = c.index, DataTime = c.datatime }; var message = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(pm)); Console.WriteLine("{0} time: {1}", pm.Name, DateTime.Now); model.BasicPublish("HistroyCity", "CityPublished", null, message); var pC = cityTable.publish.First(r => r.index == c.index); pC.ispublished = true; } cityTable.SaveChanges(); } catch (Exception err) { Console.WriteLine(err.Message); } } } } } Console.WriteLine("*****************"); Thread.Sleep(1200000); } while (true); #endregion break; case "2": #region 将消息放入到消息队列中(日值数据) var userName = config.AppSettings.Settings["UserName"]; var Password = config.AppSettings.Settings["Password"]; var Port = config.AppSettings.Settings["Port"]; var HostName = config.AppSettings.Settings["HostName"]; var factory2 = new RabbitMQ.Client.ConnectionFactory() { UserName = userName.Value, Password = Password.Value, Port = int.Parse(Port.Value), HostName = HostName.Value }; using (var connect = factory2.CreateConnection()) { using (var model = connect.CreateModel()) { model.ExchangeDeclare("HistroyCity", "direct", true); var q = model.QueueDeclare("CitiesQueue", true, false, false, null); var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(model); model.BasicQos(0, 1, false); consumer.Received += (channel, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var p = JsonConvert.DeserializeObject <PublishMessage>(message); List <data> datalist = new List <data>(); PhantomJSOptions option = new PhantomJSOptions(); option.AddAdditionalCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"); //using (var seleminun = new PhantomJSDriver(option)) using (var seleminun = new ChromeDriver()) { string t = HttpUtility.UrlDecode(string.Format("{0}{1}", p.DataTime.Value.Year, p.DataTime.Value.Month.ToString("00"))); var name = HttpUtility.UrlEncode(p.Name.Trim()); Console.WriteLine("{0}\t time:\t{1}", p.Name, DateTime.Now); string url = string.Format("https://www.aqistudy.cn/historydata/daydata.php?city={0}&month={1}", name, t); seleminun.Navigate().GoToUrl(url); Thread.Sleep(new Random().Next(90000, 180000)); var rowEs = seleminun.FindElements(By.XPath("//div[@class=\"row\"]/div/table/tbody/tr")); Console.WriteLine(rowEs.Count); for (int rowIndex = 1; rowIndex < rowEs.Count; rowIndex++) { var trEs = rowEs[rowIndex].FindElements(By.XPath(".//td")); var tempdata = new data() { name = p.Name }; tempdata.date = DateTime.Parse(trEs[0].Text); tempdata.aqi = trEs[1].Text; tempdata.rank = trEs[2].Text; int p25, p10, so2, no2, O3_8h; double co; if (int.TryParse(trEs[3].Text, out p25)) { tempdata.pm2d5 = p25; } if (int.TryParse(trEs[4].Text, out p10)) { tempdata.pm10 = p10; } if (int.TryParse(trEs[5].Text, out so2)) { tempdata.so2 = so2; } if (double.TryParse(trEs[6].Text, out co)) { tempdata.co = co; } if (int.TryParse(trEs[7].Text, out no2)) { tempdata.no2 = no2; } if (int.TryParse(trEs[8].Text, out O3_8h)) { tempdata.o3_8 = O3_8h; } tempdata.updatetime = DateTime.Now; datalist.Add(tempdata); } } if (datalist.Count > 0) { var publisher = new PublishData(); publisher.Publish(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(datalist))); } model.BasicAck(ea.DeliveryTag, false); }; model.BasicConsume("CitiesQueue", false, consumer); var r = Console.ReadLine(); if (r.ToLower().Trim() == "over") { return; } } } #endregion break; case "3": #region 获取队列中的数据 var factory4 = new RabbitMQ.Client.ConnectionFactory() { UserName = "******", Password = "******", Port = 5672, HostName = "47.101.160.52" }; using (var connect = factory4.CreateConnection()) { using (var model = connect.CreateModel()) { model.ExchangeDeclare("HistroyCity", "direct", true); var q = model.QueueDeclare("CitiesDataQueue", true, false, false, null); var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(model); model.BasicQos(0, 1, false); consumer.Received += (channel, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); var datalist = JsonConvert.DeserializeObject <List <data> >(message); using (var enty = new HistoryDataEntities()) { foreach (var item in datalist) { enty.data.Add(item); Console.WriteLine("{0} time:{1}", item.name, DateTime.Now); } enty.SaveChanges(); } model.BasicAck(ea.DeliveryTag, false); GC.Collect(); }; model.BasicConsume("CitiesDataQueue", false, consumer); var r = Console.ReadLine(); if (r.ToLower().Trim() == "over") { return; } } } #endregion break; case "4": #region 在数据库中插入任务计划 Console.WriteLine("请输入时间:YYYY-MM-DD"); string dateStr = Console.ReadLine(); var splits = dateStr.Split(new string[] { "-", "—", "_" }, StringSplitOptions.RemoveEmptyEntries); if (splits.Length != 3) { break; } using (var cityTable = new HistoryDataEntities()) { var list = (from c in cityTable.cities select c).ToArray(); foreach (var c in list) { var p = new publish(); p.name = c.name; p.homeurl = c.homeurl; p.datatime = new DateTime(int.Parse(splits[0]), int.Parse(splits[1]), 1); p.ispublished = false; cityTable.publish.Add(p); } cityTable.SaveChanges(); Console.WriteLine(cityTable.publish.Count()); Console.WriteLine("*****************"); } Console.WriteLine("*****************"); #endregion break; default: break; } }
static void Main(string[] args) { string queuqname = "firstQueue"; ushort limitnum = 3; try { #region 构建消息队列 //1.实例化连接工厂 var factory = new RabbitMQ.Client.ConnectionFactory(); factory.HostName = "localhost"; factory.UserName = "******"; factory.Password = "******"; factory.AutomaticRecoveryEnabled = true; //2. 建立连接 var connection = factory.CreateConnection(); //3. 创建信道 var channel = connection.CreateModel(); var queue_name = queuqname; //项目下游上传的队列信息 bool durable = true; //队列是否持久化 bool exclusive = false; //设置 autoDeleted=true 的队列,当没有消费者之后,队列会自动被删除 bool autoDelete = false; //4. 申明队列 channel.QueueDeclare(queue_name, durable, exclusive, autoDelete, null); //5. 构造消费者实例 var consumer = new RabbitMQ.Client.Events.EventingBasicConsumer(channel); bool autoAck = false; //autoAck:true;自动进行消息确认,当消费端接收到消息后,就自动发送ack信号,不管消息是否正确处理完毕 //autoAck:false;关闭自动消息确认,通过调用BasicAck方法手动进行消息确认 //6. 绑定消息接收后的事件委托 //8. 启动消费者 //设置prefetchCount : 3 来告知RabbitMQ,在未收到消费端的N条消息确认时,不再分发消息,也就确保了当消费端处于忙碌状态时 channel.BasicQos(0, limitnum, false); channel.BasicConsume(queue_name, autoAck, consumer); #endregion #region 队列-接收消息的处理方法 consumer.Received += (model, ea) => { try { //var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(ea.Body.ToArray()); //获取消息后进行操作,do something bool flag = false; if (!string.IsNullOrEmpty(message)) { try { //做其他存储或处理操作 //File.WriteAllText(@"C:\Users\Administrator\Desktop\333.txt", message, Encoding.UTF8); Console.WriteLine("接收消息:" + message); flag = true; } catch (Exception ex) { } } else { flag = true; } if (flag) { //操作完毕,则手动确认消息可删除 // 7. 发送消息确认信号(手动消息确认) channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); } } catch (Exception ex) { } }; #endregion } catch (Exception ex) { } //finally //{ // connection.Close();//不能关,关了就停止接收消息了 // channel.Close(); //} Console.ReadKey(); }
static void Main(string[] args) { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "logs", type: "fanout"); channel.QueueDeclare(queue: "1ToMany2", durable: false, exclusive: false, autoDelete: false, arguments: null); channel.QueueBind(queue: "1ToMany2", exchange: "logs", routingKey: ""); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); }; channel.BasicConsume(queue: "1ToMany2", noAck: true, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } }