public void Should_raise_message_returned_event_when_message_returned() { const string exchange = "the exchange"; const string replyText = "reply text"; const string routingKey = "routing key"; var body = new byte[0]; var properties = new BasicProperties(); publisher.Publish(channelMock, model => { }).Wait(); channelMock.Raise(x => x.BasicReturn += null, null, new BasicReturnEventArgs { Body = body, Exchange = exchange, ReplyText = replyText, RoutingKey = routingKey, BasicProperties = properties }); var arg = eventBus.GetArgumentsForCallsMadeOn(x => x.Publish(Arg<ReturnedMessageEvent>.Is.Anything))[0][0]; var messageEvent = arg as ReturnedMessageEvent; Assert.NotNull(messageEvent); Assert.AreSame(body, messageEvent.Body); Assert.NotNull(messageEvent.Properties); Assert.AreEqual(exchange, messageEvent.Info.Exchange); Assert.AreEqual(replyText, messageEvent.Info.ReturnReason); Assert.AreEqual(routingKey, messageEvent.Info.RoutingKey); }
static void Main(string[] args) { var exchg = "socketIOdemo"; Console.WriteLine("Creating factory..."); var factory = new ConnectionFactory(); Console.WriteLine("Creating connection..."); factory.Protocol = Protocols.FromEnvironment(); factory.HostName = "localhost"; var ser = new JavaScriptSerializer(); using (var conn = factory.CreateConnection()) using (IModel ch = conn.CreateModel()) { Console.WriteLine("Creating exchange..."); ch.ExchangeDeclare(exchg, ExchangeType.Fanout, true); var props = new BasicProperties() { ContentType = "application/json" }; while (true) { Console.Write("> "); var txt=Console.ReadLine(); var msg = new Message{ body = txt }; var serMsg = ser.Serialize(msg); var messageBody = Encoding.UTF8.GetBytes(serMsg); ch.BasicPublish(exchg, string.Empty, props, messageBody); } } }
protected void DeliverMessage(string correlationId, string exceptionMessage) { var properties = new BasicProperties { Type = "EasyNetQ.Tests.TestResponseMessage:EasyNetQ.Tests.Messages", CorrelationId = correlationId, Headers = new Dictionary<string, object> { { "IsFaulted", true } } }; if (exceptionMessage != null) { // strings are implicitly convertered in byte[] from RabbitMQ client // but not convertered back in string // check the source code in the class RabbitMQ.Client.Impl.WireFormatting properties.Headers.Add("ExceptionMessage", Encoding.UTF8.GetBytes(exceptionMessage)); } var body = Encoding.UTF8.GetBytes("{}"); mockBuilder.Consumers[0].HandleBasicDeliver( "consumer_tag", 0, false, "the_exchange", "the_routing_key", properties, body ); }
public void Should_be_able_to_subscribe_using_non_generic_extensions() { var are = new AutoResetEvent(false); MyMessage deliveredMessage = null; Action<object> onMessage = message => { deliveredMessage = (MyMessage)message; are.Set(); }; mockBuilder.Bus.Subscribe(typeof (MyMessage), "subid", onMessage); var properties = new BasicProperties { Type = "EasyNetQ.Tests.MyMessage:EasyNetQ.Tests" }; var body = Encoding.UTF8.GetBytes("{ Text:\"Hello World\" }"); mockBuilder.Consumers[0].HandleBasicDeliver( "consumer_tag", 0, false, "exchange", "routing_key", properties, body); are.WaitOne(1000); deliveredMessage.ShouldNotBeNull(); deliveredMessage.Text.ShouldEqual("Hello World"); }
public void SetUp() { mockBuilder = new MockBuilder(); var queue = new Queue("test_queue", false); var are = new AutoResetEvent(false); mockBuilder.Bus.Advanced.Consume<ITestMessageInterface>(queue, (message, info) => Task.Factory.StartNew(() => { receivedMessage = message.Body; are.Set(); })); var publishedMessage = new Implementation { Text = "Hello Polymorphs!" }; var body = new JsonSerializer(new TypeNameSerializer()).MessageToBytes(publishedMessage); var properties = new BasicProperties { Type = new TypeNameSerializer().Serialize(typeof(Implementation)) }; mockBuilder.Consumers[0].HandleBasicDeliver( "consumer_tag", 0, false, "exchange", "routing_key", properties, body ); are.WaitOne(1000); }
static void Main(string[] args) { var factory = new ConnectionFactory { HostName = "localhost", UserName = "******", Password = "******" }; var factory2 = new ConnectionFactory { HostName = "datdb.cphbusiness.dk", UserName = "******", Password = "******", Port = 5672 }; var connection = factory.CreateConnection(); var cphConnection = factory2.CreateConnection(); var channel = connection.CreateModel(); channel.QueueDeclare("Bank1Requests", true, false, false, null); var cphExchange = cphConnection.CreateModel(); cphExchange.ExchangeDeclare("cphbusiness.bankXML", "fanout"); var consumer = new EventingBasicConsumer(); consumer.Model = channel; consumer.Received += (s, e) => { var msg = e.Body.ToRequestMessage<CreditScoreMessage>(); var properties = new BasicProperties(); properties.ReplyTo = "channel78"; cphExchange.BasicPublish("cphbusiness.bankXML", "cphbusiness.bankXML", properties, string.Format(@"<LoanRequest> <ssn>{0}</ssn> <creditScore>{1}</creditScore> <loanAmount>{2}</loanAmount> <loanDuration>{3}</loanDuration> </LoanRequest>", msg.Ssn, msg.CreditScore, msg.Amount, new DateTime(1970, 1, 1).AddDays(msg.Duration).ToString("yyyy-MM-dd " + "00:00:00.0 CET")).ToByteArray()); }; channel.BasicConsume("Bank1Requests", true, consumer); var cphConsumer = new EventingBasicConsumer(); var cphChannel = cphConnection.CreateModel(); cphChannel.QueueDeclare("channel78", true, false, false, null); cphConsumer.Model = cphChannel; cphConsumer.Received += (s, e) => { int i = 0; }; cphChannel.BasicConsume("channel78", true, cphConsumer); }
public void Should_copy_from_Rabbit_client_properties() { const string replyTo = "reply to"; var properties = new MessageProperties(); var originalProperties = new BasicProperties {ReplyTo = replyTo}; properties.CopyFrom(originalProperties); properties.ReplyTo.ShouldEqual(replyTo); }
protected override void DispatchMessage(object msg) { Performance<RabbitPerformance>.Counter.IncreaseMessagesProcessedPerSecond(); Performance<RabbitPerformance>.Counter.IncreaseThreadsUsedPerSecond(); try { if (Log.IsDebugEnabled) Log.Debug("Handling message on thread: {0}", Thread.CurrentThread.ManagedThreadId); var rabbitMsg = (RabbitMessage)msg; var newScope = ComponentLocator.Current.StartChildScope(); IMessage result; using (newScope) { new MessagePipeline(MessageHandlerProvider, MessageFormatter, newScope, rabbitMsg, null).Process(out result); } var correlationId = rabbitMsg.Properties.CorrelationId; var queueName = rabbitMsg.Properties.ReplyTo; if (String.IsNullOrEmpty(correlationId) || String.IsNullOrEmpty(queueName)) return; if (Log.IsInfoEnabled) Log.Info("Message has CorrelationId: {0} and response will be sent to: {1}", correlationId, queueName); var channel = Connection.Current.CreateModel(); IBasicProperties props = new BasicProperties { CorrelationId = correlationId }; var payload = MessageFormatter.Format(result); if (Log.IsDebugEnabled) Log.Debug("Publishing response."); channel.BasicPublish(String.Empty, queueName, props, payload); if (Log.IsDebugEnabled) Log.Debug("Published response."); } catch (Exception ex) { Log.Error("Exception in message handling", ex); } finally { QueueUsedThreads--; Performance<RabbitPerformance>.Counter.DecrementThreadsCurrentlyUsed(); } }
// ReSharper disable ConditionIsAlwaysTrueOrFalse public static void Exec(bool durable, bool ack, IModel model, IConnection connection) { var queueName = "CSharpPublish" + (durable ? "Durable" : "NotDurable"); if (!string.IsNullOrWhiteSpace(_overrideQueueName)) queueName = _overrideQueueName; Console.WriteLine("Durability {0} enabled", durable ? "IS" : "is NOT"); Console.WriteLine("ACK {0} enabled", ack ? "IS" : "is NOT"); Console.WriteLine("Creating queue {0}...", queueName); model.QueueDeclare(queueName, durable, false, false, null); var msg = Encoding.UTF8.GetBytes("Hello from my PC !"); var properties = new BasicProperties { DeliveryMode = (byte)(durable ? 2 : 1) }; if (_publish) { for (int i = 0; i < _numMsgs; i++) model.BasicPublish(string.Empty, queueName, properties, msg); Console.WriteLine("Published!"); } uint msgs = 0; if (_receive) { Console.WriteLine("Reading..."); var fromMac = false; while (connection.IsOpen) { var result = model.BasicGet(queueName, ack == false); if (result == null) break; if (msgs % 3144 == 0) Console.WriteLine(msgs); if (ack) model.BasicAck(result.DeliveryTag, false); var msgText = Encoding.UTF8.GetString(result.Body); if (msgText.Contains("Mac")) fromMac = true; msgs++; } if (fromMac) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Received messages from the mac"); Console.ResetColor(); } } }
private static Envelope CreateMessage(String streamId, String type, IDictionary<String, Object> body) { var meta = new BasicProperties { AppId = Assembly.GetExecutingAssembly().GetName().Name, Type = type, MessageId = Guid.NewGuid().ToString(), Timestamp = new AmqpTimestamp(DateTime.UtcNow.Ticks), Headers = new ListDictionary {{"streamId", streamId}} }; return new Envelope() { Body = body, Meta = meta }; }
public void Should_copy_to_rabbit_client_properties() { const string replyTo = "reply to"; var properties = new MessageProperties { ReplyTo = replyTo }; var destinationProperties = new BasicProperties(); properties.CopyTo(destinationProperties); destinationProperties.ReplyTo.ShouldEqual(replyTo); destinationProperties.IsReplyToPresent().ShouldBeTrue(); destinationProperties.IsMessageIdPresent().ShouldBeFalse(); }
public void An_exchange_is_bound_to_a_queue() { Model.ExchangeDeclare("TypeA", ExchangeType.Fanout, true, true, null); _queueName = Model.QueueDeclare("TypeA", true, true, true, null); Model.QueueBind(_queueName, "TypeA", ""); Model.QueuePurge(_queueName); byte[] message = Encoding.UTF8.GetBytes("HELLO, WORLD."); IBasicProperties properties = new BasicProperties(); properties.Type = "System.string"; Model.BasicPublish("TypeA", "", properties, message); }
public void PublishMessagesToQueue(IEnumerable<HosepipeMessage> messages, QueueParameters parameters) { using (var connection = HosepipeConnection.FromParamters(parameters)) using (var channel = connection.CreateModel()) { foreach (var message in messages) { var body = Encoding.UTF8.GetBytes(message.Body); var properties = new BasicProperties(); message.Properties.CopyTo(properties); channel.BasicPublish(message.Info.Exchange, message.Info.RoutingKey, properties, body); } } }
/// <summary> /// delivery the message directly into the queue from which it came. /// /// You may want to put it back into an exchange instead of a queue. /// </summary> private void SendMessageToQueue(string queueName, byte[] messageBytes) { const string exchangeName = ""; if (string.IsNullOrEmpty(queueName)) { throw new ArgumentNullException("queueName"); } if (messageBytes == null) { throw new ArgumentNullException("messageBytes"); } var basicProperties = new BasicProperties { DeliveryMode = 2//2 = durable }; _model.BasicPublish(exchangeName, queueName, basicProperties, messageBytes); }
protected void ReturnResponse() { var body = Encoding.UTF8.GetBytes("{ \"Text\": \"Hello World!\" }"); var properties = new BasicProperties { Type = "EasyNetQ_Tests_MyOtherMessage:EasyNetQ_Tests" }; var consumerTag = "the_consumer_tag"; var autoResetEvent = new AutoResetEvent(false); var handlerRunning = (HandlerRunner)mockBuilder.ServiceProvider.Resolve<IHandlerRunner>(); handlerRunning.OnAckSent = () => autoResetEvent.Set(); mockBuilder.Consumers[0].HandleBasicDeliver(consumerTag, 0, false, "", "rpc_return_queue", properties, body); autoResetEvent.WaitOne(500); }
public void HandlingLastErrorMessageCallsFallback() { var basicProperties = new BasicProperties(); basicProperties.SetRetryCount(3); var basicDeliverEventArgs = new BasicDeliverEventArgs(Guid.NewGuid().ToString(), 0, false, "Test", "Test", basicProperties, new byte[16]); _sut.HandleConsumerError(basicDeliverEventArgs, new Exception("Test")); Thread.Sleep(TimeSpan.FromSeconds(4)); _model.AssertWasNotCalled(x => x.BasicPublish(null, null, null, null), y => y.IgnoreArguments()); _fallbackStrategy.AssertWasCalled(x => x.HandleConsumerError(null, null), y => y.IgnoreArguments() .Message("Expected invocation of fallback strategy!")); _logger.AssertWasNotCalled(x => x.ErrorWrite(null, null), y => y.IgnoreArguments() .Message("RetryMessageConsumerErrorStrategy should not be called any more at this point!")); }
public void HandleSecondErroredMessage() { var basicProperties = new BasicProperties(); basicProperties.SetRetryCount(2); var basicDeliverEventArgs = new BasicDeliverEventArgs(Guid.NewGuid().ToString(), 0, false, "Test", "Test", basicProperties, new byte[16]); _sut.HandleConsumerError(basicDeliverEventArgs, new Exception("Test")); Thread.Sleep(TimeSpan.FromSeconds(4)); _model.AssertWasCalled(x => x.BasicPublish(Arg<string>.Is.Equal("Test"), Arg<string>.Is.Equal("Test"), Arg<IBasicProperties>.Matches(z => z.GetRetryCount() == 3), Arg<byte[]>.Is.Anything)); _logger.AssertWasNotCalled(x => x.ErrorWrite(null, null), y => y.IgnoreArguments()); }
private void DeliverMessage(string message, string type) { var properties = new BasicProperties { Type = type, CorrelationId = "the_correlation_id" }; var body = Encoding.UTF8.GetBytes(message); mockBuilder.Consumers[0].HandleBasicDeliver( "consumer tag", 0, false, "the_exchange", "the_routing_key", properties, body ); WaitForMessageDispatchToComplete(); }
public void RegisterResponseAction(Action<IMessage> responseAction, out IBasicProperties basicProperties) { var correlationId = Guid.NewGuid().ToString(); basicProperties = new BasicProperties { ReplyTo = _queueName, CorrelationId = correlationId, DeliveryMode = 1 }; _responseHandlers.Add(correlationId, responseAction); }
public void SendResponse(MessageContext context, HttpResponsePacket response ) { if (disposed) throw new ObjectDisposedException("Subscriber has been disposed"); if (String.IsNullOrEmpty(context.ReplyToQueue)) return; if (conn == null) { //TODO: Log this -- it technically shouldn't happen. Also translate to a HTTP Unreachable because it means StartCallbackQueueConsumer didn't create a connection throw new ApplicationException("This is Bad"); } //TODO: Channel Pool this connection using (IModel channel = conn.CreateModel()) { BasicProperties basicProperties = new BasicProperties { CorrelationId = context.CorrelationId }; try { channel.BasicPublish(String.Empty, context.ReplyToQueue, basicProperties, response.Serialize()); } catch { //TODO: Log execption } } }
static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory { HostName = "192.168.16.53", Port = 5672, UserName = "******", Password = "******", VirtualHost = "/" }; var pubConnection = factory.CreateConnection(); var consumeConnection = factory.CreateConnection(); using (var channel = pubConnection.CreateModel()) { channel.ExchangeDeclare(ExchangeName, ExchangeType.Headers, false, false, null); //Dictionary<string, object> headers = null; Dictionary<string, object> headers = new Dictionary<string, object>(); headers["asd"] = "asd"; channel.QueueDeclare(QueueNameOne, true, false, false, headers); channel.QueueBind(QueueNameOne, ExchangeName, String.Empty, headers); //channel.QueueDeclare(QueueNameTwo, true, false, false, null); //channel.QueueBind(QueueNameTwo, ExchangeName, String.Empty); } var pool = new WorkPool("MyPoool", 5); for (int i = 0; i < 5; i++) { pool.AddWork(new Consumer(factory.CreateConnection())); } pool.StartCrawlers(); //for (int i = 0; i < 5; i++) //{ // Task.Factory.StartNew(() => // { // using (var channel = consumeConnection.CreateModel()) // { // var consumer = new QueueingBasicConsumer(channel); // channel.BasicConsume(QueueNameOne, true, consumer); // while (true) // { // consumer.Queue.Dequeue(); // } // } // }); //} for (int i = 0; i < 2; i++) { var message = BuildBytes(200); Task.Factory.StartNew(() => { using (var channel = pubConnection.CreateModel()) { IBasicProperties props = new BasicProperties(); props.SetPersistent(true); props.Priority = 9; props.Headers = new Dictionary<string, object>() { { "asd", "asd" } }; while (true) { for (int j = 0; j < 100; j++) { channel.BasicPublish(ExchangeName, string.Empty, false, false, props, message); } } } }); } }
private IBasicProperties GetBasicProperties(AsyncLogEventInfo loggingEvent) { var @event = loggingEvent.LogEvent; var basicProperties = new BasicProperties(); basicProperties.ContentEncoding = "utf8"; basicProperties.ContentType = "text/plain"; basicProperties.AppId = AppId ?? @event.LoggerName; basicProperties.Timestamp = new AmqpTimestamp( Convert.ToInt64((@event.TimeStamp - _Epoch).TotalSeconds)); // support Validated User-ID (see http://www.rabbitmq.com/extensions.html) basicProperties.UserId = UserName; return basicProperties; }
private void PublishKeepAlive(IModel ch) { var keepAlive = _sensuClientConfigurationReader.Configuration.Config["client"]; keepAlive["timestamp"] = SensuClientHelper.CreateTimeStamp(); keepAlive["version"] = Version; // Undocumented stuff to send the client version keepAlive["plugins"] = ""; List<string> redactlist = null; redactlist = SensuClientHelper.GetRedactlist((JObject) keepAlive); var payload = SensuClientHelper.RedactSensitiveInformaton(keepAlive, redactlist); Log.Debug("Publishing keepalive"); var properties = new BasicProperties { ContentType = "application/octet-stream", Priority = 0, DeliveryMode = 1 }; try { ch.BasicPublish("", "keepalives", properties, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload))); } catch (Exception) { Log.Error("Lost MQ connection when trying to publish keepalives!"); } }
private static void Receive(IModel model, QueueingBasicConsumer consumer) { var request = consumer.Queue.Dequeue() as BasicDeliverEventArgs; if (request == null) { Console.WriteLine("Request is NULL!"); return; } else { var requestObj = request.Body.Deserialize<GetDateRequest>(); Console.WriteLine("[Server] Received Request: {0}", requestObj.ToJson()); // Ack the request model.BasicAck(request.DeliveryTag, false); // Create a reply var replyQueue = request.BasicProperties.ReplyTo; var correlationId = request.BasicProperties.CorrelationId; var replyObj = new GetDateResponse {Timestamp = DateTime.Now}; var replyProperties = new BasicProperties { CorrelationId = correlationId, }; // Send the reply Console.WriteLine("[Server] Sending reply..."); model.BasicPublish("", replyQueue, replyProperties, replyObj.Serialize()); // Now receive the next message Receive(model, consumer); } }
public void PublishResult(JObject payload) { var json = JsonConvert.SerializeObject(payload); Log.Info("Publishing Check to sensu server {0} \n", json); using (var ch = _connectionFactory.GetRabbitConnection().CreateModel()) { var properties = new BasicProperties { ContentType = "application/octet-stream", Priority = 0, DeliveryMode = 1 }; ch.BasicPublish("", "results", properties, Encoding.UTF8.GetBytes(json)); } }
public static void Send(object sender, System.Timers.ElapsedEventArgs e) { Task.Factory.StartNew(() => { try { if (_connection == null) return; // create a new channel in this thread var sendChannel = _connection.CreateModel(); // new correlation ID for this request var myCorrelationId = Guid.NewGuid().ToString(); // declare a queue for me to read the response var myQueue = sendChannel.QueueDeclare(); // set the correlationId and replyTo queue in the basic properties (this could be done in the Body/Application Layer, but the features are built into AMQP) var requestProperties = new BasicProperties { ReplyTo = myQueue.QueueName, CorrelationId = myCorrelationId, }; // Publish a send message sendChannel.BasicPublish("", _incomingRequests, requestProperties, new GetDateRequest { Name = myCorrelationId }.Serialize()); Console.WriteLine("[Client] Sent request. Correlation ID {0}", myCorrelationId); // Now we need to wait for a reply var queuedConsumer = new QueueingBasicConsumer(sendChannel); sendChannel.BasicConsume(myQueue.QueueName, false, queuedConsumer); // Now we wait for a response! var response = queuedConsumer.Queue.Dequeue() as BasicDeliverEventArgs; if (response == null) throw new InvalidOperationException("No response!"); var correlationId = response.BasicProperties.CorrelationId; Console.WriteLine("[Client] Received reply for {0}", correlationId); // Deserialize the repsonse var responseObj = response.Body.Deserialize<GetDateResponse>(); Console.WriteLine("[Client] Received timestamp {0} it is now {1}\r\n----------------------------------\r\n\r\n", responseObj.Timestamp, DateTime.Now); } catch (Exception ex) { WriteException(ex); } }); }
private static void PublishResult(JObject check) { var payload = new JObject(); payload["check"] = check; payload["client"] = _configsettings["client"]["name"]; Log.Info("Publishing Check {0}", JsonConvert.SerializeObject(payload, SerializerSettings)); using (var ch = GetRabbitConnection().CreateModel()) { var properties = new BasicProperties { ContentType = "application/octet-stream", Priority = 0, DeliveryMode = 1 }; ch.BasicPublish("", "results", properties, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload))); } ChecksInProgress.Remove(check["name"].ToString()); }
protected void DeliverMessage(string correlationId) { var properties = new BasicProperties { Type = "EasyNetQ.Tests.TestResponseMessage:EasyNetQ.Tests.Messages", CorrelationId = correlationId }; var body = Encoding.UTF8.GetBytes("{ Id:12, Text:\"Hello World\"}"); mockBuilder.Consumers[0].HandleBasicDeliver( "consumer_tag", 0, false, "the_exchange", "the_routing_key", properties, body ); }
private static void KeepAliveScheduler() { IModel ch = null; Log.Debug("Starting keepalive scheduler thread"); while (true) { if (ch == null || !ch.IsOpen) { Log.Error("rMQ Q is closed, Getting connection"); var connection = GetRabbitConnection(); if (connection == null) { //Do nothing - we'll loop around the while loop again with everything null and retry the connection. } else { ch = connection.CreateModel(); } } if (ch != null && ch.IsOpen) { //Valid channel. Good to publish. var payload = _configsettings["client"]; payload["timestamp"] = Convert.ToInt64( Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds, MidpointRounding.AwayFromZero)); Log.Debug("Publishing keepalive"); var properties = new BasicProperties { ContentType = "application/octet-stream", Priority = 0, DeliveryMode = 1 }; ch.BasicPublish("", "keepalives", properties, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload))); } else { Log.Error("Valiant attempts to get a valid rMQ connection were in vain. Skipping this keepalive loop."); } //Lets us quit while we're still sleeping. lock (MonitorObject) { if (_quitloop) { Log.Warn("Quitloop set, exiting main loop"); break; } Monitor.Wait(MonitorObject, KeepAliveTimeout); if (_quitloop) { Log.Warn("Quitloop set, exiting main loop"); break; } } } }
public void An_exchange_is_bound_to_a_highly_available_queue() { var args = new Hashtable(); args.Add("x-ha-policy", "all"); Model.ExchangeDeclare("TypeA", ExchangeType.Fanout, true, true, null); _queueName = Model.QueueDeclare("TypeA", true, true, true, args); Model.QueueBind(_queueName, "TypeA", ""); Model.QueuePurge(_queueName); byte[] message = Encoding.UTF8.GetBytes("HELLO, WORLD."); IBasicProperties properties = new BasicProperties(); properties.Type = "System.string"; Model.BasicPublish("TypeA", "", properties, message); }