Example #1
0
        /// <summary>
        /// Creates and fills MapMessageBuilder for publish message into broker.
        /// </summary>
        /// <param name="message">Incoming message.</param>
        /// <param name="model">AMQP-model.</param>
        /// <returns>MapMessageBuilder with filled body header properties.</returns>
        private MapMessageBuilder BuildMessage(ServiceBusMessage message, IModel model)
        {
            var messageBuilder = new MapMessageBuilder(model);

            messageBuilder.Properties.DeliveryMode = 2;

            int normalizedPriority = (message.Priority < 0 ? 0 :
                                      message.Priority > 9 ? 9 :
                                      message.Priority);

            messageBuilder.Properties.Priority = Convert.ToByte(normalizedPriority);

            var bodyProps = _messageConverter.GetBodyProperties(message);

            foreach (var bodyProp in bodyProps)
            {
                messageBuilder.Body.Add(bodyProp.Key, bodyProp.Value);
            }

            var headerProps = _messageConverter.GetProperties(message);

            if (messageBuilder.Properties.Headers == null)
            {
                messageBuilder.Properties.Headers = headerProps;
            }
            else
            {
                foreach (var headerProp in headerProps)
                {
                    messageBuilder.Properties.Headers.Add(headerProp.Key, headerProp.Value);
                }
            }

            return(messageBuilder);
        }
Example #2
0
        protected byte[] ProduceObjectData(IPipelineObject item)
        {
            var keyValues = item.Serialize();

            IMapMessageBuilder b = new MapMessageBuilder(Model);

            foreach (KeyValuePair <string, string> keyValue in keyValues)
            {
                b.Body[keyValue.Key] = keyValue.Value;
            }
            return(b.GetContentBody());
        }
Example #3
0
        /// <summary>
        /// 插入队列
        /// </summary>
        /// <param name="body">消息内容</param>
        /// <param name="queuename">队列名称</param>
        public bool ProduceMessage(string body, string queuename)
        {
            if (string.IsNullOrEmpty(body))
            {
                throw new ArgumentNullException("body");
            }
            CheckConn();
            //创建并返回一个新连接到具体节点的通道
            using (IModel ch = conn.CreateModel())
            {
                try
                {
                    if (RBSendinfo.ExchangeType != null)
                    {   //声明一个路由
                        ch.ExchangeDeclare(RBSendinfo.Exchange, RBSendinfo.ExchangeType);
                        //声明一个队列
                        if (!string.IsNullOrEmpty(queuename))
                        {
                            ch.QueueDeclare(queuename, true, false, false, null);

                            //将一个队列和一个路由绑定起来。并制定路由关键字
                            ch.QueueBind(queuename, RBSendinfo.Exchange, RBSendinfo.RoutingKey);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new RabbitException()
                          {
                              InternalException = ex, QueueName = queuename, RabbitInfo = RBSendinfo.ToString(), CurrentMessage = ""
                          };
                }
                ///构造消息实体对象并发布到消息队列上
                IMapMessageBuilder b      = new MapMessageBuilder(ch);
                IDictionary        target = b.Headers;
                target["header"] = "RabbitQ";
                IDictionary targerBody = b.Body;
                targerBody["body"] = body;//这个才是具体的发送内容
                if (persistMode)
                {
                    ((IBasicProperties)b.GetContentHeader()).DeliveryMode = 2;
                    //设定传输模式
                }
                //写入
                ch.BasicPublish(RBSendinfo.Exchange, RBSendinfo.RoutingKey, (IBasicProperties)b.GetContentHeader(), b.GetContentBody());
                return(true);
            }
        }
Example #4
0
        public static int Main(string[] args)
        {
            bool persistMode = false;

            int optionIndex = 0;

            while (optionIndex < args.Length)
            {
                if (args[optionIndex] == "/persist")
                {
                    persistMode = true;
                }
                else
                {
                    break;
                }
                optionIndex++;
            }

            if (((args.Length - optionIndex) < 1) ||
                (((args.Length - optionIndex - 1) % 2) == 1))
            {
                Console.Error.WriteLine("Usage: SendMap [<option> ...] <exchange-uri> [[<key> <value>] ...]");
                Console.Error.WriteLine("RabbitMQ .NET client version " + typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Exchange-URI: amqp://host[:port]/exchange[/routingkey][?type=exchangetype]");
                Console.Error.WriteLine("Keys must start with '+' or with '-'. Those starting with '+' are placed in");
                Console.Error.WriteLine("the body of the message, and those starting with '-' are placed in the headers.");
                Console.Error.WriteLine("Values must start with a single character typecode and a colon.");
                Console.Error.WriteLine("Supported typecodes are:");
                Console.Error.WriteLine(" S - string/byte array");
                Console.Error.WriteLine(" x - byte array (base-64)");
                Console.Error.WriteLine(" t - boolean");
                Console.Error.WriteLine(" i - 32-bit integer");
                Console.Error.WriteLine(" d - double-precision float");
                Console.Error.WriteLine(" D - fixed-point decimal");
                Console.Error.WriteLine("Note that some types are valid only in the body of a message, and some are");
                Console.Error.WriteLine("valid only in the headers.");
                Console.Error.WriteLine("The exchange \"amq.default\" is an alias for the default (\"\") AMQP exchange,");
                Console.Error.WriteLine("introduced so that the default exchange can be addressed via URI syntax.");
                Console.Error.WriteLine("Available options:");
                Console.Error.WriteLine("  /persist     send message in 'persistent' mode");
                return(2);
            }

            Uri    uri          = new Uri(args[optionIndex++]);
            string exchange     = uri.Segments[1].TrimEnd(new char[] { '/' });
            string exchangeType = uri.Query.StartsWith("?type=") ? uri.Query.Substring(6) : null;
            string routingKey   = uri.Segments.Length > 2 ? uri.Segments[2] : "";

            if (exchange == "amq.default")
            {
                exchange = "";
            }

            ConnectionFactory cf = new ConnectionFactory();

            cf.Endpoint = new AmqpTcpEndpoint(uri);

            using (IConnection conn = cf.CreateConnection())
            {
                using (IModel ch = conn.CreateModel()) {
                    if (exchangeType != null)
                    {
                        ch.ExchangeDeclare(exchange, exchangeType);
                    }

                    IMapMessageBuilder b = new MapMessageBuilder(ch);
                    while ((optionIndex + 1) < args.Length)
                    {
                        string keyAndDiscriminator = args[optionIndex++];
                        string valueAndType        = args[optionIndex++];

                        if (keyAndDiscriminator.Length < 1)
                        {
                            Console.Error.WriteLine("Invalid key: '{0}'", keyAndDiscriminator);
                            return(2);
                        }
                        string key           = keyAndDiscriminator.Substring(1);
                        char   discriminator = keyAndDiscriminator[0];

                        IDictionary <string, object> target;
                        switch (discriminator)
                        {
                        case '-':
                            target = b.Headers;
                            break;

                        case '+':
                            target = b.Body;
                            break;

                        default:
                            Console.Error.WriteLine("Invalid key: '{0}'",
                                                    keyAndDiscriminator);
                            return(2);
                        }

                        if (valueAndType.Length < 2 || valueAndType[1] != ':')
                        {
                            Console.Error.WriteLine("Invalid value: '{0}'", valueAndType);
                            return(2);
                        }
                        string valueStr = valueAndType.Substring(2);
                        char   typeCode = valueAndType[0];

                        object value;
                        switch (typeCode)
                        {
                        case 'S':
                            value = valueStr;
                            break;

                        case 'x':
                            value = new BinaryTableValue(Convert.FromBase64String(valueStr));
                            break;

                        case 't':
                            value = (valueStr.ToLower() == "true" ||
                                     valueStr.ToLower() == "yes" ||
                                     valueStr.ToLower() == "on" ||
                                     valueStr == "1");
                            break;

                        case 'i':
                            value = int.Parse(valueStr);
                            break;

                        case 'd':
                            value = double.Parse(valueStr);
                            break;

                        case 'D':
                            value = decimal.Parse(valueStr);
                            break;

                        default:
                            Console.Error.WriteLine("Invalid type code: '{0}'", typeCode);
                            return(2);
                        }

                        target[key] = value;
                    }
                    if (persistMode)
                    {
                        ((IBasicProperties)b.GetContentHeader()).DeliveryMode = 2;
                    }
                    ch.BasicPublish(exchange,
                                    routingKey,
                                    (IBasicProperties)b.GetContentHeader(),
                                    b.GetContentBody());
                    return(0);
                }
            }
        }