Esempio n. 1
0
        /// <summary>
        /// Listens on the specified queue for incoming messages.
        /// </summary>
        /// <param name="queue"></param>
        public void ReceiveMessage(string queue)
        {
            if (string.IsNullOrEmpty(queue))
            {
                return;
            }

            using (var connection = RabbitConnection.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: 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($"Hello {StringHelper.GetNameAfterCharacter(message, ',')}, I am your father!");
                    };
                    channel.BasicConsume(queue, true, consumer);

                    Console.WriteLine(" Press [enter] to exit.");
                    Console.ReadLine();
                }
        }
Esempio n. 2
0
        /// <summary>
        /// 初始化异常处理
        /// </summary>
        private void InitExceptionHandle()
        {
            // 如果有定义异常处理
            if (amqpQueue.ExceptionHandle == null || amqpQueue.ExceptionHandle.PublishConsumers.IsNullOrLength0())
            {
                return;
            }

            // 查找不重复的主机ID数组
            var hostIds = amqpQueue.ExceptionHandle.PublishConsumers.Select(p => p.HostId).Distinct().ToArray();

            exceptionHandleConnections = new RabbitConnection[hostIds.Length];
            for (var i = 0; i < hostIds.Length; i++)
            {
                exceptionHandleConnections[i] = new RabbitConnection();
                exceptionHandleConnections[i].OpenByHostId(hostIds[i]);
            }

            dicExceptionHandleProducers = new Dictionary <IProducer, string>(amqpQueue.ExceptionHandle.PublishConsumers.Length);
            foreach (var pc in amqpQueue.ExceptionHandle.PublishConsumers)
            {
                var conn     = exceptionHandleConnections.Where(p => p.HostId == pc.HostId).FirstOrDefault();
                var producer = conn.CreateProducer(pc.Exchange);

                dicExceptionHandleProducers.Add(producer, pc.RoutingKey);
            }
        }
Esempio n. 3
0
        public CreditEnricher(string receiveQueueName, string sendToQueueName)
        {
            rabbitConn            = new RabbitConnection();
            this.receiveQueueName = receiveQueueName;
            this.sendToQueueName  = sendToQueueName;

            #region Declaring Queues Notes

            /* Source: https://www.rabbitmq.com/tutorials/amqp-concepts.html
             * Before a queue can be used it has to be declared. Declaring a queue will cause it to be created if it does not already exist.
             * The declaration will have no effect if the queue does already exist and its attributes are the same as those in the declaration.
             * When the existing queue attributes are not the same as those in the declaration a channel-level exception with code 406(PRECONDITION_FAILED) will be raised.
             * Queue properties:
             *  Durable (the queue will survive a broker restart)
             *  Exclusive (used by only one connection and the queue will be deleted when that connection closes)
             *  Auto-delete (queue is deleted when last consumer unsubscribes)
             *  Arguments (some brokers use it to implement additional features like message TTL)
             */

            #endregion Declaring Queues Notes

            //Declare the queues needed in this program, sets durable to true in case of RabbitMQ breakdown.
            rabbitConn.Channel.QueueDeclare(queue: receiveQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
            rabbitConn.Channel.QueueDeclare(queue: sendToQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
        }
Esempio n. 4
0
        /// <summary>
        /// 业务调用RPC服务端
        /// </summary>
        private static void BusinessCallRpcServer()
        {
            // 创建Rabbit连接和Rpc服务端
            var conn = new RabbitConnection();

            conn.OpenByHostId("host1");
            var rpcServer = conn.CreateRpcServer("RpcExchange", "RpcQueue");

            // 创建Rpc监听服务
            var listen = new RpcServerListen();

            // 设置接口映射配置文件
            var mapImplCache = new InterfaceMapImplCache();

            mapImplCache.Set(new DictionaryJson("Config/interfaceAssemblyMapImplAssemblyConfig.json"));

            // 将映射赋值到监听中
            listen.InterfaceMapImpl = mapImplCache;

            // 将RPC服务设置到监听中
            listen.RpcServer          = rpcServer;
            listen.BytesSerialization = new MessagePackBytesSerialization();

            // 注册错误事件
            listen.ReceivingError += Listen_ReceivingError;

            // 开始监听
            Console.WriteLine("监听Rpc服务的请求:");
            listen.ListenAsync();
        }
Esempio n. 5
0
        public static Configuration StartRabbitMQ(this Configuration configuration)
        {
            var setting = configuration.Setting.GetRabbitMQSetting();

            foreach (var type in _metadatas)
            {
                var instance = (IRabbitMessagingHandler)ObjectContainer.Resolve(type);
                if (!instance.IsEnable)
                {
                    continue;
                }
                if (IsStop(setting, instance.Queue))
                {
                    Log.Warn($"The queue has stop in the config. queue({instance.Queue})");
                    continue;
                }
                if (string.IsNullOrWhiteSpace(instance.Name))
                {
                    throw new ArgumentNullException($"The virtualhost is null in the handler({instance.GetType().Name})!");
                }
                var hostSetting   = setting.GetServer(instance.Name) ?? throw new ArgumentNullException($"The handler name({instance.Name}) cannot found setting!");
                var rabbitContext = new RabbitConnection(instance.Queue, instance.Exchange, instance.RoutingKey, hostSetting, instance.Handle);
                Task.Run(() => { rabbitContext.Start(); });
            }
            _metadatas = null;
            return(configuration);
        }
Esempio n. 6
0
 public Translator(string receiveQueueName, string sendToQueueName)
 {
     rabbitConn            = new RabbitConnection();
     this.receiveQueueName = receiveQueueName;
     this.sendToQueueName  = sendToQueueName;
     rabbitConn.Channel.QueueDeclare(queue: receiveQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
     rabbitConn.Channel.QueueDeclare(queue: sendToQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
 }
Esempio n. 7
0
 public Bank(string receiveQueueName)
 {
     //Connects to RabbitMQ server
     rabbitConn            = new RabbitConnection();
     this.receiveQueueName = receiveQueueName;
     //Declare the queues needed in this program, sets durable to true in case of RabbitMQ breakdown.
     rabbitConn.Channel.QueueDeclare(queue: receiveQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
 }
        public string InvokeLoanBroker(string ssn, double amount, int duration)
        {
            LoanRequest      loanRequest = new LoanRequest();
            RabbitConnection rabbitConn  = new RabbitConnection();

            //set message body content
            loanRequest.SSN      = ssn;
            loanRequest.Amount   = amount;
            loanRequest.Duration = duration;

            string msg = loanRequest.ToString();
            //set message header properties
            //give the message a corrId
            string           corrId = Guid.NewGuid().ToString();
            IBasicProperties prop   = rabbitConn.Channel.CreateBasicProperties();

            prop.CorrelationId = corrId;
            //give message a temp reply queue
            string tempreplyQueueName = rabbitConn.Channel.QueueDeclare().QueueName;
            string replyQueueName     = tempreplyQueueName.Replace("amq", "groupB.tmp.reply");

            prop.ReplyTo = replyQueueName;

            //send message
            rabbitConn.Send(msg, "groupB.loanRequest", prop, false);

            //Wait for answer
            rabbitConn.Channel.QueueDeclare(queue: replyQueueName, durable: false, exclusive: true, autoDelete: false, arguments: null);
            var consumer = new QueueingBasicConsumer(rabbitConn.Channel);

            rabbitConn.Channel.BasicConsume(queue: replyQueueName,
                                            noAck: false,
                                            consumer: consumer);
            string response = null;

            //sync receiving
            while (true)
            {
                var ea = consumer.Queue.Dequeue();

                var body   = ea.Body;
                var header = ea.BasicProperties;

                if (header.CorrelationId == corrId)
                {
                    response = Encoding.UTF8.GetString(body);
                    rabbitConn.Channel.BasicAck(ea.DeliveryTag, false);
                    break;
                }
                //release the message back on to the queue
                rabbitConn.Channel.BasicReject(ea.DeliveryTag, true);
            }

            return(response);
        }
        /// <summary>
        /// 设置消息队列读取
        /// </summary>
        /// <param name="conn">消息队列连接</param>
        /// <param name="reader">消息队列读取</param>
        public static void SetMessageQueueReader(this IMessageQueueConnection conn, IRabbitMessageQueueReader reader)
        {
            if (conn == null)
            {
                return;
            }

            RabbitConnection rabbitConn = null;

            if (conn is RabbitAutoRecoveryConnection)
            {
                var autoRabbitConn = conn as RabbitAutoRecoveryConnection;
                if (autoRabbitConn.ProtoConnection == null)
                {
                    autoRabbitConn.ProtoConnection = new RabbitConnection();
                }
                else if (autoRabbitConn.ProtoConnection is RabbitConnection)
                {
                    rabbitConn = autoRabbitConn.ProtoConnection as RabbitConnection;
                }
                else
                {
                    throw new NotSupportedException("RabbitAutoRecoveryConnection.ProtoConnection不是RabbitConnection");
                }
            }
            else if (conn is RabbitConnection)
            {
                rabbitConn = conn as RabbitConnection;
            }
            else
            {
                throw new NotSupportedException("不支持的连接类型,必须是RabbitConnection");
            }

            RabbitMessageQueueInfoConfigFactory msgQueueConfigFactoy = null;

            if (rabbitConn.MessageQueueInfoFactory == null)
            {
                msgQueueConfigFactoy = new RabbitMessageQueueInfoConfigFactory();
                rabbitConn.MessageQueueInfoFactory = msgQueueConfigFactoy;
            }
            else if (rabbitConn.MessageQueueInfoFactory is RabbitMessageQueueInfoConfigFactory)
            {
                msgQueueConfigFactoy = rabbitConn.MessageQueueInfoFactory as RabbitMessageQueueInfoConfigFactory;
            }
            else
            {
                throw new NotSupportedException("消息队列信息工厂不支持的类型,必须是RabbitMessageQueueInfoConfigFactory");
            }

            msgQueueConfigFactoy.MessageQueueReader = reader;
        }
Esempio n. 10
0
 public Scatter(string receiveQueueName)
 {
     rabbitConn            = new RabbitConnection();
     this.receiveQueueName = receiveQueueName;
     rabbitConn.Channel.QueueDeclare(queue: receiveQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
     rabbitConn.Channel.QueueDeclare(queue: "groupB.json.bank.translator", durable: true, exclusive: false, autoDelete: false, arguments: null);
     rabbitConn.Channel.QueueDeclare(queue: "groupB.xml.bank.translator", durable: true, exclusive: false, autoDelete: false, arguments: null);
     rabbitConn.Channel.QueueDeclare(queue: "groupB.our.bank.translator", durable: true, exclusive: false, autoDelete: false, arguments: null);
     rabbitConn.Channel.QueueDeclare(queue: "groupB.web.bank.translator", durable: true, exclusive: false, autoDelete: false, arguments: null);
     rabbitConn.Channel.QueueDeclare(queue: "groupB.json.bank.reply", durable: true, exclusive: false, autoDelete: false, arguments: null);
     rabbitConn.Channel.QueueDeclare(queue: "groupB.xml.bank.reply", durable: true, exclusive: false, autoDelete: false, arguments: null);
     rabbitConn.Channel.QueueDeclare(queue: "groupB.our.bank.reply", durable: true, exclusive: false, autoDelete: false, arguments: null);
 }
Esempio n. 11
0
        public IConnection Connect()
        {
            RabbitConnection  options = new RabbitConnection();
            ConnectionFactory factory = new ConnectionFactory();

            factory.UserName    = Connection.UserName;
            factory.Password    = Connection.Password;
            factory.VirtualHost = Connection.VirtualHost;
            factory.HostName    = Connection.HostName;

            IConnection conn = factory.CreateConnection();

            return(conn);
        }
Esempio n. 12
0
        public async void RequestModelPublisherRemoteProcedureCallTest()
        {
            // Arrange
            var connectionMock        = new Mock <IConnection>();
            var connectionFactoryMock = new Mock <IConnectionFactory>();

            connectionFactoryMock.Setup(cf => cf.CreateConnection()).Returns(connectionMock.Object);
            var rabbitConnection = Sys.ActorOf(RabbitConnection.CreateProps(connectionFactoryMock.Object));

            // Act
            var consumerActorRef = await rabbitConnection.Ask <IActorRef>(Mock.Of <IRequestModelPublisherRemoteProcedureCall>());

            // Assert
            Assert.IsNotNull(consumerActorRef);
        }
Esempio n. 13
0
        /// <summary>
        /// 发送邮件 正常情况下应该使用 MQ 来解耦发送邮件 -- 后面改为MQ
        /// </summary>
        /// <param name="title">邮件主题</param>
        /// <param name="htmlContent">邮件内容</param>
        /// <param name="emailTo">收件人邮箱  可以用分号分隔 发送到多个</param>
        /// <param name="emailToName">收件人姓名</param>
        /// <returns></returns>
        public async Task <string> SendSystemMailAsync(string title, string htmlContent, string emailTo, string emailToName = null)
        {
            if (title.IsNullOrEmpty() || htmlContent.IsNullOrEmpty() || emailTo.IsNullOrEmpty())
            {
                return("发送失败,参数不允许为空!");
            }
            var mailBo = new MailBo(IConfiguration)
            {
                MailToName = emailToName,
                MailTo     = emailTo
            };
            var mqMailBo = new MqMailBo()
            {
                MailBo      = mailBo,
                Title       = title,
                HtmlContent = htmlContent
            };

            using (var channel = RabbitConnection.CreateModel())
            {
                channel.QueueDeclare(queue: "LionEmailQueue",
                                     durable: true,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);
                channel.ConfirmSelect();                              //等待发送成功确认
                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;                         //持久化
                properties.MessageId  = IdWorker.NextId().ToString(); //消息Id
                properties.Timestamp  = new AmqpTimestamp(DateTime.Now.GetJsTimeStamp());
                properties.Headers    = new Dictionary <string, object>();
                var bodyJson = mqMailBo.ToJson();
                var body     = Encoding.UTF8.GetBytes(bodyJson);
                channel.BasicPublish(exchange: "",
                                     routingKey: "LionEmailQueue",
                                     basicProperties: properties,
                                     body: body);
                var isOk = channel.WaitForConfirms();
                if (isOk)
                {
                    return("发送成功");
                }

                //日志记录
                LogHelper.Logger.Error($"邮件保存MQ失败,bodyJson:{bodyJson}");
                return("发送异常");
            }
        }
Esempio n. 14
0
            public void should_close_connection_on_channel_failure()
            {
                var bus = this.ConfigureBus("Test", cfg => { });
                var tcs = new TaskCompletionSource <bool>();

                var connection = new RabbitConnection(new Endpoint("test"), bus.Configuration.ConnectionString, bus);

                connection.Closed += (sender, args) => tcs.SetResult(true);

                connection.Open(CancellationToken.None);
                var channel = connection.OpenChannel();

                channel.Abort();
                channel.Bind(Queue.Named("q").Instance, Exchange.Named("e").Instance, "key");

                Assert.IsTrue(tcs.Task.Result);
            }
Esempio n. 15
0
        static void Main(string[] args)
        {
            var conn = new RabbitConnection();

            conn.OpenByHostId("exhost");
            var consumer = conn.CreateConsumer("ExChange", "ExQueue");

            Console.WriteLine("监听业务异常信息:");

            consumer.Subscribe((BusinessExceptionInfo msg) =>
            {
                Console.WriteLine(msg.ToString());

                return(true);
            });

            Console.Read();
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            Console.WriteLine("这里是接收MQ业务异常处理:");

            var conn = new RabbitConnection();

            conn.OpenByHostId("exhost");
            var consumer = conn.CreateConsumer("ExChange", "ExQueue");

            consumer.Subscribe((BusinessExceptionInfo busEx) =>
            {
                Console.WriteLine("接收到异常数据:" + busEx);

                return(true);
            });

            Console.Read();
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            ConnectionFactory factory = new ConnectionFactory
            {
                UserName    = "******",
                Password    = "******",
                HostName    = "localhost",
                Port        = 5672,
                VirtualHost = "/",
            };

            //const string exchangeName = "amq.topic";
            const string exchangeName = "";
            const string routingKey   = "routingKey";


            var actorSystem = ActorSystem.Create("RabbitAkkaExample");

            var rabbitConnectionActorRef = actorSystem.ActorOf(RabbitConnection.CreateProps(factory));

            var rabbitPublisher = rabbitConnectionActorRef.Ask <IActorRef>(new RequestModelPublisher(true, TimeSpan.FromSeconds(10))).Result;

            var consoleOutputOne = actorSystem.ActorOf(ConsoleOutputActorThatReplies.CreateProps("One", 3000, rabbitPublisher));
            var consoleOutputTwo = actorSystem.ActorOf(ConsoleOutputActorThatReplies.CreateProps("Two", 6000, rabbitPublisher));

            var rabbitModelOne = rabbitConnectionActorRef.Ask <IActorRef>(new RequestModelConsumerWithConcurrencyControl(
                                                                              exchangeName,
                                                                              "xxx",//"one",
                                                                              routingKey,
                                                                              1,
                                                                              consoleOutputOne)).Result;

            var rabbitModelTwo = rabbitConnectionActorRef.Ask <IActorRef>(new RequestModelConsumerWithConcurrencyControl(
                                                                              exchangeName,
                                                                              "xxx", //"two",
                                                                              routingKey,
                                                                              3,
                                                                              consoleOutputTwo)).Result;

            Task.WaitAll(rabbitModelOne.Ask <bool>("start"),
                         rabbitModelTwo.Ask <bool>("start"));

            Console.ReadLine();
        }
Esempio n. 18
0
        public Aggregator(string receiveQueueName, string requestInfoQueueName)
        {
            bankCount = 0;
            //set timer props
            aTimer           = new Timer();
            aTimer.Interval  = 30000;
            aTimer.Enabled   = false;
            aTimer.AutoReset = false;

            requests  = new Dictionary <IBasicProperties, LoanRequest>();
            responses = new List <LoanResponse>();
            //Connects to RabbitMQ server
            rabbitConn            = new RabbitConnection();
            this.receiveQueueName = receiveQueueName;

            this.requestInfoQueueName = requestInfoQueueName;
            rabbitConn.Channel.QueueDeclare(queue: requestInfoQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
            rabbitConn.Channel.QueueDeclare(queue: receiveQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
        }
Esempio n. 19
0
        /// <summary>
        /// Publishes messages to the specified queue.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="queque"></param>
        public bool PublishMessage(string message, string queque)
        {
            if (string.IsNullOrEmpty(message) || string.IsNullOrEmpty(queque))
            {
                return(false);
            }

            using (var connection = RabbitConnection.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queque, false, false, false, null);

                    var body = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish("", queque, null, body);
                }

            return(true);
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            var conn = new RabbitConnection();

            conn.OpenByHostId("host1");
            Console.WriteLine("请输入要消费的队列名:");
            var quque    = Console.ReadLine();
            var consumer = conn.CreateConsumer("TestExchange", quque);

            consumer.Subscribe((string msg) =>
            {
                Console.WriteLine("接收到数据:" + msg);

                //throw new Exception("测试业务处理异常"); //这里抛出异常,会自动发送到异常队列里

                return(true);
            });

            Console.Read();
        }
Esempio n. 21
0
            public void should_not_close_connection_on_channel_failure()
            {
                var bus = this.ConfigureBus("Test", cfg => { });
                var tcs = new TaskCompletionSource <bool>(true);

                var connection = new RabbitConnection(new Endpoint("test"), bus.Configuration.ConnectionString, bus);

                connection.Closed += (sender, args) => tcs.SetResult(false);

                var tokenSource = new CancellationTokenSource();

                connection.Open(tokenSource.Token);
                var channel = connection.OpenChannel(tokenSource.Token);

                channel.Abort();
                Assert.Throws <AlreadyClosedException>(
                    () => channel.Bind(Queue.Named("q").Instance, Exchange.Named("e").Instance, "key"));

                Assert.True(!tcs.Task.IsCompleted);
            }
Esempio n. 22
0
 /// <summary>
 ///  重试 死信 测试
 /// </summary>
 /// <param name="msg"></param>
 /// <returns></returns>
 public async Task <string> RetryDeadLetterMqSendAsync(string msg)
 {
     using (var channel = RabbitConnection.CreateModel())
     {
         channel.ExchangeDeclare("TestExchange", ExchangeType.Direct, true);
         channel.QueueDeclare("TestQueue", true, false, false);
         channel.QueueBind("TestQueue", "TestExchange", "TestRouteKey");
         channel.ConfirmSelect();                              //等待发送确认
         var properties = channel.CreateBasicProperties();
         properties.Persistent = true;                         //设置为持久化
         properties.MessageId  = IdWorker.NextId().ToString(); //消息Id
         var body = msg.GetBytes();
         channel.BasicPublish("TestExchange", "TestRouteKey", properties, body);
         var isOk = channel.WaitForConfirms(TimeSpan.FromSeconds(3));
         if (isOk)
         {
             return("发送成功");
         }
     }
     return("发送失败");
 }
Esempio n. 23
0
        /// <summary>
        /// 简单RPC客户端
        /// </summary>
        private static void SimpleRpcClient()
        {
            var conn = new RabbitConnection();

            conn.OpenByHostId("host1");
            var rpcClient = conn.CreateRpcClient("RpcExchange", "RpcQueue");

            Console.WriteLine("请输入要给RPC服务端发送的消息:");
            while (true)
            {
                var msg = Console.ReadLine();
                if ("exit".Equals(msg))
                {
                    break;
                }

                var re    = rpcClient.Call(Encoding.UTF8.GetBytes(msg));
                var reStr = re.IsNullOrLength0() ? null : Encoding.UTF8.GetString(re);
                Console.WriteLine("服务端返回:" + reStr);
            }
        }
Esempio n. 24
0
        public RabbitConnectionManager(IOptions <RabbitConnection> rabbitConnectionOptions, ILogger <RabbitConnectionManager> logger)
        {
            _logger           = logger;
            _rabbitConnection = rabbitConnectionOptions.Value;
            _logger.LogInformation("Connection {ConnectionName} is in use.", _rabbitConnection.ConnectionName);
            Connection = new ConnectionFactory()
            {
                HostName                = _rabbitConnection.HostName,
                Port                    = _rabbitConnection.Port,
                VirtualHost             = _rabbitConnection.VirtualHost,
                UserName                = _rabbitConnection.UserName,
                Password                = _rabbitConnection.Password,
                DispatchConsumersAsync  = _rabbitConnection.DispatchConsumersAsync,
                TopologyRecoveryEnabled = _rabbitConnection.TopologyRecoveryEnabled,
                RequestedHeartbeat      = _rabbitConnection.RequestedHeartbeat,
                NetworkRecoveryInterval = TimeSpan.FromMilliseconds(_rabbitConnection.NetworkRecoveryInterval)
            }.CreateConnection();

            Connection.ConnectionShutdown += (sender, reason) => {
                _logger.LogInformation("Connection {ConnectionName} closed. Reason: {@ShutdownEventArgs}", _rabbitConnection.ConnectionName.ToString(), reason);
            };
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            var conn = new RabbitConnection();

            conn.OpenByHostId("host1");
            var producer = conn.CreateProducer("TestExchange");

            Console.WriteLine("请输入要生产的路由键:");
            var key = Console.ReadLine();

            Console.WriteLine("请输入要发送的消息:");
            while (true)
            {
                var msg = Console.ReadLine();
                if ("exit".Equals(msg))
                {
                    break;
                }

                producer.Publish(msg, key);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// 简单RPC服务端
        /// </summary>
        private static void SimpleRpcServer()
        {
            var conn = new RabbitConnection();

            conn.OpenByHostId("host1");
            var rpcServer = conn.CreateRpcServer("RpcExchange", "RpcQueue");

            Console.WriteLine("监听Rpc服务的请求:");

            rpcServer.Receive(msg =>
            {
                var str = Encoding.UTF8.GetString(msg);

                Console.WriteLine(str);

                if ("exception".Equals(str))
                {
                    throw new Exception("RPC Server 业务处理异常");
                }

                return(Encoding.UTF8.GetBytes("已收到"));
            });
        }
Esempio n. 27
0
        public static IConnection Connect(RabbitContext ctx)
        {
            RabbitConnection  options = ctx.Connection;
            ConnectionFactory factory = new ConnectionFactory();

            if (!string.IsNullOrWhiteSpace(options.UserName))
            {
                factory.UserName = options.UserName;
            }
            if (!string.IsNullOrWhiteSpace(options.Password))
            {
                factory.Password = options.Password;
            }
            if (!string.IsNullOrWhiteSpace(options.UserName))
            {
                factory.VirtualHost = options.VirtualHost;
            }

            factory.HostName = options.HostName;
            IConnection conn = factory.CreateConnection();

            return(conn);
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            //Thread.Sleep(TimeSpan.FromHours(1));
            ConnectionFactory factory = new ConnectionFactory
            {
                UserName    = "******",
                Password    = "******",
                HostName    = "localhost",
                Port        = 5672,
                VirtualHost = "/",
            };

            //const string exchangeName = "amq.topic";
            const string exchangeName = "";
            const string routingKey   = "routingKey";


            var actorSystem = ActorSystem.Create("RabbitAkkaExample");

            var rabbitConnectionActorRef = actorSystem.ActorOf(RabbitConnection.CreateProps(factory));

            var requestModelPublisherActorRef =
                rabbitConnectionActorRef.Ask <IActorRef>(new RequestModelPublisher(true, TimeSpan.FromSeconds(10))).Result;

            var consoleOutputActorRef = actorSystem.ActorOf(ConsoleOutputActor.CreateProps());

            var requestModelPublisherRemoteProcedureCallActorRef =
                rabbitConnectionActorRef.Ask <IActorRef>(new RequestModelPublisherRemoteProcedureCall(exchangeName, routingKey, consoleOutputActorRef)).Result;

            string input = null;

            do
            {
                Task <bool> publishTask = null;
                if (input?.StartsWith("?", StringComparison.CurrentCultureIgnoreCase) == true)
                {
                    if (string.IsNullOrEmpty(exchangeName))
                    {
                        publishTask = requestModelPublisherRemoteProcedureCallActorRef.Ask <Task <bool> >(new PublishMessageToQueue(
                                                                                                              "xxx",
                                                                                                              Encoding.ASCII.GetBytes(input.Substring(1)))).Result;
                    }
                    else
                    {
                        publishTask = requestModelPublisherRemoteProcedureCallActorRef.Ask <Task <bool> >(new PublishMessageUsingRoutingKey(
                                                                                                              exchangeName, routingKey, Encoding.ASCII.GetBytes(input.Substring(1)))).Result;
                    }
                }
                else if (input != null)
                {
                    if (string.IsNullOrEmpty(exchangeName))
                    {
                        publishTask = requestModelPublisherActorRef.Ask <Task <bool> >(new PublishMessageToQueue("xxx",
                                                                                                                 Encoding.ASCII.GetBytes(input))).Result;
                    }
                    else
                    {
                        publishTask = requestModelPublisherActorRef.Ask <Task <bool> >(new PublishMessageUsingRoutingKey(exchangeName, routingKey,
                                                                                                                         Encoding.ASCII.GetBytes(input))).Result;
                    }
                }

                if (publishTask != null)
                {
                    var messageInput = input;
                    publishTask.ContinueWith(_ => Console.WriteLine($"Published {messageInput}"),
                                             TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
                    publishTask.ContinueWith(_ => Console.WriteLine($"Could not publish {messageInput}"),
                                             TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.AttachedToParent);
                }
                Console.WriteLine("type message to send, prefix with [?] for rpc (enter [q] to exit)");
                input = Console.ReadLine();
            } while (!"q".Equals(input, StringComparison.CurrentCultureIgnoreCase));

            Task.WaitAll(actorSystem.Terminate());
        }
Esempio n. 29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = new RabbitConnection
            {
                ConnectionFactory = new ConnectionFactory
                {
                    HostName = "127.0.0.1",
                    Port     = 5672,
                    UserName = "******",
                    Password = "******"
                }
            };


            var clientOption = new RabbitClientOptions
            {
                ClientName   = Guid.NewGuid().ToString("N"),
                ClientUnique = Guid.NewGuid().ToString("N").Substring(0, 6),
                Connection   = connection
            };

            services.AddRabbitClient(provider => clientOption);
            //services.AddHttpClient<PersonalClient>().ConfigurePrimaryRabbitMessageHandler(connection.ConnectionFactory, provider => clientOption);

            //services.AddHttpClient<PersonalClient>().ConfigurePrimaryHttpMessageHandler(provider => provider.GetService<NatsMessageHandler>());

            //services.AddHttpClient<PersonalClient>().ConfigurePrimaryKafkaMessageHandler(provider => new KafkaOptions
            //{
            //	ProducerConfig = new ProducerConfig { BootstrapServers = "localhost:9092" },
            //	ConsumerConfig = new ConsumerConfig
            //	{
            //		ClientId = "test",
            //		GroupId = "test-consumer-group",
            //		BootstrapServers = "localhost:9092",
            //		AutoOffsetReset = AutoOffsetReset.Earliest
            //	}
            //});
            //var options = NATS.Client.ConnectionFactory.GetDefaultOptions();
            //options.Name = "localhost";
            //options.Servers = new[] { "nats://localhost:4222" };

            //services.AddNatsClient(provider => new NatsQueueClientOption
            //{
            //	Options = options
            //});

            //	adminBuilder.
            //	.AddNatsServer(provider => new NatsServerOption
            //{
            //	Options = options,
            //	Server = new Uri("nats://localhost")
            //});
            //services.AddKafkaServer(provider => new KafkaServerOption
            //{
            //	Server = new List<Uri> {new Uri("kafka://localhost")},
            //	ProducerConfig = new ProducerConfig {BootstrapServers = "localhost:9092"},
            //	ConsumerConfig = new ConsumerConfig
            //	{
            //		ClientId = "personal-area",
            //		GroupId = "test-consumer-group",
            //		BootstrapServers = "localhost:9092",
            //		AutoOffsetReset = AutoOffsetReset.Earliest
            //	}
            //});
            services.AddRabbitServer(new RabbitServerOptions
            {
                Connection   = connection,
                DelayOptions = new DelayOptions
                {
                    QueueOptions = DelayOptions.CreateInterval().Take(3).ToList()
                },
                Queue = new AppQueueOption
                {
                    Uri = new Uri("rabbitmq://localhost")
                }
            });
            services.Configure <RabbitMessageHandler>(handler =>
            {
                handler.Factory = null;
            });
            services.AddControllers();
        }
        public static IServiceCollection AddRabbitMqConnection(this IServiceCollection services, RabbitConnection rabbitConnection)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if (rabbitConnection == null || rabbitConnection.ConnectionName == string.Empty)
            {
                throw new ArgumentNullException(nameof(rabbitConnection));
            }

            services.AddLogging();
            services.AddOptions();
            services.Configure <RabbitConnection>(opts => {
                opts.AutomaticRecoveryEnabled = rabbitConnection.AutomaticRecoveryEnabled;
                opts.ClientProperties         = rabbitConnection.ClientProperties;
                opts.ConnectionName           = rabbitConnection.ConnectionName;
                opts.DispatchConsumersAsync   = rabbitConnection.DispatchConsumersAsync;
                opts.HostName = rabbitConnection.HostName;
                opts.NetworkRecoveryInterval = rabbitConnection.NetworkRecoveryInterval;
                opts.Password                = rabbitConnection.Password;
                opts.Port                    = rabbitConnection.Port;
                opts.PrefetchCount           = rabbitConnection.PrefetchCount;
                opts.RequestedHeartbeat      = rabbitConnection.RequestedHeartbeat;
                opts.TopologyRecoveryEnabled = rabbitConnection.TopologyRecoveryEnabled;
                opts.UserName                = rabbitConnection.UserName;
                opts.VirtualHost             = rabbitConnection.VirtualHost;
            });
            services.AddSingleton <IRabbitConnectionManager, RabbitConnectionManager>();
            return(services);
        }