Example #1
0
        //private void Close()
        //{
        //    _chanel.Close();
        //    _connection.Close();
        //}

        public void SendMessage(string queueName, string message)
        {
            Open();
            //todo 发送消息
            _chanel.QueueDeclare(queueName, false, false, true, null);
            var bytes = Encoding.UTF8.GetBytes(message);

            _chanel.BasicPublish("", queueName, null, bytes);
            //Console.WriteLine("发送消息");
            //Close();
        }
        protected virtual void DoPublish(RC.IModel channel, Address replyTo, IMessage <byte[]> message)
        {
            var props = channel.CreateBasicProperties();

            MessagePropertiesConverter.FromMessageHeaders(message.Headers, props, EncodingUtils.GetEncoding(Encoding));
            channel.BasicPublish(replyTo.ExchangeName, replyTo.RoutingKey, MandatoryPublish, props, message.Payload);
        }
 public void PublishEvent <T>(T @event) where T : IEvent
 {
     using (IConnection conn = connectionFactory.CreateConnection())
     {
         using (RabbitMQ.Client.IModel channel = conn.CreateModel())
         {
             var queue = @event is CustomerCreatedEvent ?
                         Constants.QUEUE_CUSTOMER_CREATED : @event is CustomerUpdatedEvent ?
                         Constants.QUEUE_CUSTOMER_UPDATED : Constants.QUEUE_CUSTOMER_DELETED;
             channel.QueueDeclare(
                 queue: queue,
                 durable: false,
                 exclusive: false,
                 autoDelete: false,
                 arguments: null
                 );
             var body = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(@event));
             channel.BasicPublish(
                 exchange: "",
                 routingKey: queue,
                 basicProperties: null,
                 body: body
                 );
         }
     }
 }
Example #4
0
        internal static void Publish(string exchangeName, string routingKey, With.Message.ISerializer messageSerializer, RabbitMQ.Client.IModel model, With.Message.IMessage message)
        {
            string content = messageSerializer.Serialize(message);

            byte[]           body       = Encoding.Encode(content);
            IBasicProperties properties = model.CreateBasicProperties();

            model.BasicPublish(exchangeName, routingKey, properties, body);
        }
Example #5
0
        public void PostMessage(IIoTHubMessage message)
        {
            if (message != null)
            {
                string json             = JsonConvert.SerializeObject(message, _serializerSettings);
                byte[] messageBodyBytes = Encoding.UTF8.GetBytes(json);

                _rmqModel.BasicPublish(_exchangeName, message.Topic, null, messageBodyBytes);
            }
        }
Example #6
0
 public async Task SendServerEventAsync(ServerEventMessage msg)
 {
     await Task.Run(() =>
     {
         using (var ms = new MemoryStream())
         {
             ProtoBuf.Serializer.Serialize(ms, msg);
             _channel.BasicPublish(_config.ExchangeName, msg.GetRoutingGey(_config.RoutingKeyPrefix), true, null,
                                   ms.ToArray());
         }
     });
 }
Example #7
0
        private void SendToMessageBus(Rmq.IModel channel, string topic, byte[] message)
        {
            var props = channel.CreateBasicProperties();

            props.Expiration = (5 * 60 * 1000).ToString(); // The message expires after 5 minutes

            // Send the message to the topic
            channel.BasicPublish(exchange: ExchangeName,
                                 routingKey: topic,
                                 mandatory: false,
                                 basicProperties: props,
                                 body: message);

            var msgToUi = string.Format("{0} Sent a message to topic {1}", DateTime.Now.ToString("HH:mm:ss"), topic);

            m_ui.PrintLine(msgToUi);
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">消息</param>
        /// <param name="routingKey">路由key</param>
        /// <returns></returns>
        public SendResult SendMessage(Message message, string routingKey)
        {
            if (_isRunning == 0)
            {
                return(new SendResult(SendStatus.Failed, null, "Couldn't send message when is not running."));
            }
            if (message == null)
            {
                return(new SendResult(SendStatus.Failed, null, "Message is null."));
            }
            if (!_topics.ContainsKey(message.Topic))
            {
                return(new SendResult(SendStatus.Failed, null, $"Topic {message.Topic} not registered."));
            }
            IRabbitMQChannel channel = null;

            try
            {
                var queueCount  = _topics[message.Topic];
                var queueId     = string.IsNullOrEmpty(routingKey) ? 0 : (Crc16.GetHashCode(routingKey) % queueCount);
                var messageId   = Guid.NewGuid().ToString();
                var createdTime = message.CreatedTime == DateTime.MinValue ? DateTime.Now : message.CreatedTime;
                if (_channelPool.TryDequeue(out Tuple <DateTime, IRabbitMQChannel> item))
                {
                    channel = item.Item2;
                }
                else
                {
                    channel = _amqpConnection.CreateModel();
                    channel.ConfirmSelect();
                }
                var properties = channel.CreateBasicProperties();
                properties.Persistent  = true;
                properties.ContentType = message.ContentType ?? string.Empty;
                properties.MessageId   = Guid.NewGuid().ToString();
                properties.Type        = message.Tag ?? string.Empty;
                properties.Timestamp   = new AmqpTimestamp(DateTime2UnixTime.ToUnixTime(createdTime));
                if (_delayedMessageEnabled && message.DelayedMilliseconds > 0)
                {
                    properties.Headers = new Dictionary <string, object>
                    {
                        { "x-delay", message.DelayedMilliseconds }
                    };
                }
                channel.BasicPublish(exchange: _delayedMessageEnabled && message.DelayedMilliseconds > 0 ? $"{message.Topic}-delayed" : message.Topic,
                                     routingKey: queueId.ToString(),
                                     mandatory: true,
                                     basicProperties: properties,
                                     body: message.Body);
                if (!channel.WaitForConfirms(_sendMsgTimeout, out bool timedOut))
                {
                    return(new SendResult(timedOut ? SendStatus.Timeout : SendStatus.Failed, null, "Wait for confirms failed."));
                }
                var storeResult = new MessageStoreResult(messageId, message.Code, message.Topic, queueId, createdTime, message.Tag);
                return(new SendResult(SendStatus.Success, storeResult, null));
            }
            catch (Exception ex)
            {
                throw new System.IO.IOException("Send message has exception.", ex);
            }
            finally
            {
                if (channel != null)
                {
                    _channelPool.Enqueue(new Tuple <DateTime, IRabbitMQChannel>(DateTime.Now, channel));
                }
            }
        }