Ejemplo n.º 1
2
        private static void SendDurableMessageToDurableQueue(IModel model)
        {
            IBasicProperties basicProperties = model.CreateBasicProperties();
            basicProperties.SetPersistent(true);
            byte[] payload = Encoding.UTF8.GetBytes("This is a persistent message from Visual Studio");
            PublicationAddress address = new PublicationAddress(ExchangeType.Topic, "DurableExchange", "durable");

            model.BasicPublish(address, basicProperties, payload);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RabbitConnection"/> class.
 /// </summary>
 /// <param name="queueName">Name of the queue.</param>
 /// <param name="connection">The connection.</param>
 /// <param name="channel">The channel.</param>
 /// <param name="publicationAddress">The publication address.</param>
 public RabbitConnection(string queueName, IConnection connection, IModel channel, PublicationAddress publicationAddress)
 {
     QueueName = queueName;
     Connection = connection;
     Channel = channel;
     PublicationAddress = publicationAddress;
 }
        /// <summary>
        /// Creates an event publisher.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns></returns>
        public IDataPublisher CreatePublisher(Uri uri)
        {
            if (uri.Scheme == "rabbitmq")
            {
                var pathParts = uri.Segments;
                var queuePath = pathParts[1].TrimEnd('/');

                var model = _connection.CreateModel();

                //_model.QueueDeclare(
                //    exchangePath,
                //    true,
                //    false,
                //    false,
                //    null);

                // construct the publication address
                var publicationAddress = new PublicationAddress(
                    ExchangeType.Direct, string.Empty, queuePath);
                // construct the publisher
                var eventPublisher = new RabbitMqDataPublisher(model, publicationAddress);
                // return the publisher
                return eventPublisher;
            }

            return null;
        }
        /// <summary>
        /// Constructor for RabbitMqClient
        /// </summary>
        /// <param name="configuration">mandatory</param>
        public RabbitMQClient(RabbitMQConfiguration configuration)
        {
            // load configuration
            _config = configuration;
            _publicationAddress = new PublicationAddress(_config.ExchangeType, _config.Exchange, _config.RouteKey);

            // initialize
            InitializeEndpoint();
        }
		protected virtual void DeclareSystemExchange(IModel channel, PublicationAddress address)
		{
			if (this.DispatchOnly || address == null)
				return;

			channel.ExchangeDeclare(address.ExchangeName, address.ExchangeType, true, false, null);
			channel.QueueDeclare(address.ExchangeName, true, false, false, null);
			channel.QueueBind(address.ExchangeName, address.ExchangeName, address.RoutingKey, null);
		}
Ejemplo n.º 6
0
        private static void ReceiveRetryMode <T>(Channel channel, Action <T, BasicDeliverEventArgs> received, MessageStructure messageStructure)
        {
            var currentChannel             = channel.CurrentChannel;
            EventingBasicConsumer consumer = new EventingBasicConsumer(currentChannel);

            consumer.Received += (ch, ea) =>
            {
                var body = Encoding.UTF8.GetString(ea.Body);
                try
                {
                    channel.Logger.LogInformation($"{messageStructure.Queue.Name} Queue 消息体{{0}}", body);
                    var message = JsonConvert.DeserializeObject <T>(body);
                    try
                    {
                        received(message, ea);
                    }
                    catch (Exception e)
                    {
                        var  properties = ea.BasicProperties;
                        long retryCount = GetRetryCount(properties);
                        if (retryCount > 3)
                        {
                            IDictionary <String, Object> headers = new Dictionary <String, Object>();
                            headers.Add("x-orig-routing-key", GetOrigRoutingKey(properties, ea.RoutingKey));
                            var address = new PublicationAddress(ExchangeType.Direct, messageStructure.Exchange.DeadLetterName, messageStructure.RoutingKey);
                            channel.Publish(CreateOverrideProperties(properties, headers), ea.Body, address);
                        }
                        else
                        {
                            IDictionary <String, Object> headers = properties.Headers;
                            if (headers == null)
                            {
                                headers = new Dictionary <String, Object>();
                                headers.Add("x-orig-routing-key", GetOrigRoutingKey(properties, ea.RoutingKey));
                            }
                            else
                            {
                                headers["x-orig-routing-key"] = GetOrigRoutingKey(properties, ea.RoutingKey);
                            }
                            var address = new PublicationAddress(ExchangeType.Direct, messageStructure.Exchange.RetryName, messageStructure.RoutingKey);
                            channel.Publish(CreateOverrideProperties(properties, headers), ea.Body, address);
                        }
                    }
                }
                catch (Exception)
                {
                    channel.Logger.LogError($"Json解析{typeof(T).Name}失败:{{0}}", body);
                    var properties = ea.BasicProperties;
                    var address    = new PublicationAddress(ExchangeType.Direct, messageStructure.Exchange.DeadLetterName, messageStructure.RoutingKey);
                    channel.Publish(properties, ea.Body, address);
                }
            };
            currentChannel.BasicConsume(messageStructure.Queue.Name, true, consumer);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RabbitMqEventPublisher"/> class.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="exchangeAddress">The exchange address.</param>
        /// <param name="address">The address.</param>
        public RabbitMqEventPublisher(IModel model, String exchangeAddress, PublicationAddress address)
        {
            var builder = new UriBuilder();
            builder.Scheme = "rabbitmq";
            builder.Host = exchangeAddress;
            builder.Path = string.Format("{0}/{1}",
                Uri.EscapeUriString(address.ExchangeName),
                Uri.EscapeUriString(address.RoutingKey));

            URI = builder.Uri;

            _model = model;
            _address = address;
        }
Ejemplo n.º 8
0
        //[SetUp]
        public void Setup()
        {
            _rabbitWrapper = new Mock<IRabbitWrapper>();
            _basicConsumer = new Mock<IQueueBasicConsumer>();
            _basicProperties = new Mock<IBasicProperties>();
            _publicationAddress = new PublicationAddress("test", "test", "test");

            _subject = new RabbitReceiverChannel(100, _rabbitWrapper.Object);
            _sharedQueue = new Mock<ISharedQueue>();
            _model = new Mock<IModel>();

            _basicConsumer.SetupGet(q => q.Queue).Returns(_sharedQueue.Object);
            //_rabbitWrapper.SetupGet(rw => rw.Channel).Returns(_model.Object);
            //_rabbitWrapper.SetupGet(rw => rw.BasicConsumer).Returns(_basicConsumer.Object);
            //_rabbitWrapper.SetupGet(rw => rw.PublicationAddress).Returns(_publicationAddress);
        }
        /// <summary>
        /// Constructor for RabbitMqClient
        /// </summary>
        /// <param name="configuration">mandatory</param>
        public RabbitMQClient(RabbitMQConfiguration configuration)
        {
            // load configuration
            _config = configuration;
            _publicationAddress = new PublicationAddress(_config.ExchangeType, _config.Exchange, _config.RouteKey);

            // Lazy 
            _modelWithPropertiesFactory = () =>
            {
                var model = GetConnectionFactory()
                    .CreateConnection()
                    .CreateModel();

                var basicProperties = model.CreateBasicProperties();
                basicProperties.DeliveryMode = (byte)_config.DeliveryMode; //persistance
                return new ModelWithProperties(model, basicProperties);
            };
        }
Ejemplo n.º 10
0
        public static void Main(string[] args)
        {
            var connectionFactory = new ConnectionFactory {HostName = Settings.RabbitMqHost};

            using (var connection = connectionFactory.CreateConnection())
            {
                using (var model = connection.CreateModel())
                {
                    model.ExchangeDeclare(Settings.RabbitMqExchange, ExchangeType.Fanout);
                    model.QueueDeclare(Settings.RabbitMqQueue, true, false, true, new Dictionary<string, object>());
                    model.QueueBind(Settings.RabbitMqQueue, Settings.RabbitMqExchange, string.Empty,new Dictionary<string, object>());

                    var publicationAddress = new PublicationAddress(ExchangeType.Fanout, Settings.RabbitMqExchange, string.Empty);
                    var basicProperties = model.CreateBasicProperties();

                    var simpleMessage = new SimpleMessage {Content = "Simple Message"};

                    model.BasicPublish(Settings.RabbitMqExchange, "", false, false, basicProperties, simpleMessage.ToByteArray());

                }
            }

            System.Console.ReadLine();
        }
Ejemplo n.º 11
0
		protected virtual void ForwardTo(BasicDeliverEventArgs message, PublicationAddress address)
		{
			Log.Debug("Forwarding message '{0}' to recipient '{1}'.", message.MessageId(), address);

			this.EnsureTransaction();
			this.Send(message, address);
			this.CurrentTransaction.Commit();
		}
Ejemplo n.º 12
0
        public ICommand Publish(ICommand command, PublicationAddress receiver, TimeSpan? timeout = null)
        {
            if (!timeout.HasValue)
                timeout = TimeSpan.MaxValue;

            var props = this.Channel.CreateBasicProperties();

            //props.AppId;
            //props.ClusterId;
            //props.CorrelationId;
            props.DeliveryMode = Constants.Persistent;
            //props.Expiration;
            //props.Headers;
            //props.MessageId;
            //props.Priority;
            //props.ProtocolClassId;
            //props.ProtocolClassName;
            //props.ReplyTo;
            props.ReplyToAddress = new PublicationAddress(this.CmdExchange.ExchangeType, this.CmdExchange.Name, this.PrivateQueue.Name);
            //props.Timestamp;
            //props.UserId;

            var reqBytes = CommandSerializer.Serialize(command);
            props.ContentEncoding = CommandSerializer.ContentEncoding;
            props.ContentType = CommandSerializer.ContentType;
            props.Type = command.GetType().FullName;

            // at this point, we're ready to send

            // set up to receive the response before the send occurs
            // so there's no chance it'll be missed
            ICommand reply = null;

            using (CancellationTokenSource cts = new CancellationTokenSource())
            {
                var ct = cts.Token;

                Task replyTask = null;
                if (command.CorrelationId.HasValue)
                {
                    props.CorrelationId = command.CorrelationId.ToString();

                    replyTask = Task.Run(() =>
                    {
                        var autoAck = false;
                        using (var subscription = new Subscription(this.Channel, this.PrivateQueue.Name, autoAck))
                        {
                            var subscriptionTimeout = TimeSpan.FromMilliseconds(100d).Milliseconds;

                            while (!ct.IsCancellationRequested)
                            {
                                BasicDeliverEventArgs eventArgs = null;
                                subscription.Next(subscriptionTimeout, out eventArgs);

                                if (eventArgs != null && !ct.IsCancellationRequested)
                                {
                                    reply = CommandDeserializer.Deserialize(eventArgs.Body) as ICommand;
                                    if (reply != null && reply.CorrelationId == command.CorrelationId)
                                    {
                                        subscription.Ack(eventArgs);
                                        break;
                                    }
                                    else
                                        subscription.Model.BasicNack(eventArgs.DeliveryTag, false, true);
                                }
                            }
                        }
                    });
                }

                // now the receiver is set up, publish the command
                this.Channel.BasicPublish(receiver, props, reqBytes);

                //Console.WriteLine("{0} Command sent ({1})", command.GetType().Name, command.CorrelationId);

                if (timeout < TimeSpan.MaxValue)
                    cts.CancelAfter(timeout.Value);

                replyTask.Wait();

                return reply;
            }
        }
 /// <summary>
 /// (Extension method) Convenience overload of BasicPublish.
 /// </summary>
 /// <remarks>
 /// The publication occurs with mandatory=false and immediate=false.
 /// </remarks>
 public static void BasicPublish(this IModel model, PublicationAddress addr, IBasicProperties basicProperties, byte[] body)
 {
     model.BasicPublish(addr.ExchangeName, addr.RoutingKey, basicProperties: basicProperties, body: body);
 }
Ejemplo n.º 14
0
 public Task Send(string exchangeName, byte[] body)
 {
     var address = new PublicationAddress("", exchangeName, "");
     var sendingMessage = new SendingMessage(address, body);
     return Send(sendingMessage);
 }
Ejemplo n.º 15
0
        /// <summary>
        /// 发布消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="channel"></param>
        /// <param name="properties"></param>
        /// <param name="body"></param>
        /// <param name="address"></param>
        public static void Publish <T>(this Channel channel, IBasicProperties properties, T body, PublicationAddress address) where T : class
        {
            var jsonb   = JsonConvert.SerializeObject(body);
            var message = Encoding.UTF8.GetBytes(jsonb);

            channel.CurrentChannel.BasicPublish(address, properties, message);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// 发布消息
 /// </summary>
 /// <param name="channel"></param>
 /// <param name="properties"></param>
 /// <param name="body"></param>
 /// <param name="address"></param>
 public static void Publish(this Channel channel, IBasicProperties properties, byte[] body, PublicationAddress address)
 {
     channel.CurrentChannel.BasicPublish(address, properties, body);
 }
 /// <summary>
 /// (Extension method) Convenience overload of BasicPublish.
 /// </summary>
 /// <remarks>
 /// The publication occurs with mandatory=false and immediate=false.
 /// </remarks>
 public static Task BasicPublish(this IModel model, PublicationAddress addr, IBasicProperties basicProperties, byte[] body)
 {
     return(model.BasicPublish(addr.ExchangeName, addr.RoutingKey, basicProperties: basicProperties, body: body));
 }
Ejemplo n.º 18
0
 public void BasicPublish(PublicationAddress addr, IBasicProperties basicProperties, byte[] body)
 {
     target.BasicPublish(addr, basicProperties, body);
 }
Ejemplo n.º 19
0
 public void BasicPublish(PublicationAddress addr, IBasicProperties basicProperties, byte[] body)
 {
     InternalModel.BasicPublish(addr, basicProperties, body);
 }
Ejemplo n.º 20
0
 public void BasicPublish(PublicationAddress addr,
                          IBasicProperties basicProperties,
                          byte[] body)
 {
     BasicPublish(addr.ExchangeName,
                  addr.RoutingKey,
                  basicProperties,
                  body);
 }
        ///<summary>Process a single request received from our
        ///subscription.</summary>
        ///<remarks>
        ///<para>
        /// If the request's properties contain a non-null, non-empty
        /// CorrelationId string (see IBasicProperties), it is assumed
        /// to be a two-way call, requiring a response. The ReplyTo
        /// header property is used as the reply address (via
        /// PublicationAddress.Parse, unless that fails, in which case it
        /// is treated as a simple queue name), and the request is
        /// passed to HandleCall().
        ///</para>
        ///<para>
        /// If the CorrelationId is absent or empty, the request is
        /// treated as one-way asynchronous event, and is passed to
        /// HandleCast().
        ///</para>
        ///<para>
        /// Usually, overriding HandleCall(), HandleCast(), or one of
        /// their delegates is sufficient to implement a service, but
        /// in some cases overriding ProcessRequest() is
        /// required. Overriding ProcessRequest() gives the
        /// opportunity to implement schemes for detecting interaction
        /// patterns other than simple request/response or one-way
        /// communication.
        ///</para>
        ///</remarks>
        public virtual void ProcessRequest(BasicDeliverEventArgs evt)
        {
            IBasicProperties properties = evt.BasicProperties;
            if (properties.ReplyTo != null && properties.ReplyTo != "") {
                // It's a request.

                PublicationAddress replyAddress = PublicationAddress.Parse(properties.ReplyTo);
                if (replyAddress == null) {
                    replyAddress = new PublicationAddress(ExchangeType.Direct,
                                                          "",
                                                          properties.ReplyTo);
                }

                IBasicProperties replyProperties;
                byte[] reply = HandleCall(evt.Redelivered,
                                          properties,
                                          evt.Body,
                                          out replyProperties);
                if (replyProperties == null) {
                    replyProperties = m_subscription.Model.CreateBasicProperties();
                }

                replyProperties.CorrelationId = properties.CorrelationId;
                m_subscription.Model.BasicPublish(replyAddress,
                                                  replyProperties,
                                                  reply);
            } else {
                // It's an asynchronous message.
                HandleCast(evt.Redelivered, properties, evt.Body);
            }
        }
Ejemplo n.º 22
0
 public void BasicPublish(PublicationAddress addr, IBasicProperties basicProperties, byte[] body)
 {
     BasicPublish(exchange: addr.ExchangeName, routingKey: addr.RoutingKey, mandatory: true, immediate: true, basicProperties: basicProperties, body: body);
 }
 /// <summary>The basic publish.</summary>
 /// <param name="addr">The addr.</param>
 /// <param name="basicProperties">The basic properties.</param>
 /// <param name="body">The body.</param>
 public void BasicPublish(PublicationAddress addr, IBasicProperties basicProperties, byte[] body) { this.channelDelegate.BasicPublish(addr, basicProperties, body); }
 ///<summary>Construct an instance that will deliver to the
 ///given address.</summary>
 public SimpleRpcClient(IModel model, PublicationAddress address)
 {
     m_model = model;
     m_address = address;
     m_subscription = null;
     m_timeout = Timeout.Infinite;
 }
Ejemplo n.º 25
0
 public void BasicPublish(PublicationAddress addr, IBasicProperties basicProperties, byte[] body)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 26
0
		protected virtual void Send(BasicDeliverEventArgs message, PublicationAddress recipient)
		{
			if (recipient == null)
				return;

			if (recipient == this.configuration.DeadLetterExchange)
				this.adapter.AppendRetryAddress(message);

			this.EnsureTransaction().Register(() => this.Try(() =>
			{
				Log.Info("Dispatching wire message '{0}' to messaging infrastructure for recipient '{1}'.", message.MessageId(), recipient);
				this.channel.BasicPublish(recipient, message.BasicProperties, message.Body);
			}));
		}
 /// <summary>
 /// (Extension method) Convenience overload of BasicPublish.
 /// </summary>
 /// <remarks>
 /// The publication occurs with mandatory=false and immediate=false.
 /// </remarks>
 public static void BasicPublish(this IModel model, PublicationAddress addr, IBasicProperties basicProperties, ReadOnlyMemory <byte> body)
 {
     model.BasicPublish(addr.ExchangeName, addr.RoutingKey, basicProperties: basicProperties, body: body);
 }
 /// <summary>
 /// Creates an event publisher.
 /// </summary>
 /// <returns></returns>
 public IEventPublisher CreatePublisher(EventPublisherArgs eventPublisherArgs)
 {
     // construct the exchange name
     var publisherTopic = CreatePublisherTopic();
     // construct the publication address
     var publicationAddress = new PublicationAddress(
         ExchangeType.Topic, _exchangePath, publisherTopic);
     // construct the publisher
     var eventPublisher = new RabbitMqEventPublisher(_model, _exchangeAddr, publicationAddress);
     // connect the statement to the publisher
     eventPublisherArgs.Statement.Events += (sender, eventArgs) => eventPublisher.SendEvent(eventArgs);
     // return the publisher
     return eventPublisher;
 }