Esempio n. 1
0
 /// <summary>
 /// 监控消费
 /// </summary>
 /// <param name="listener">消费事件</param>
 /// <param name="autoAck">是否自动确认,默认false</param>
 public void Start(IListenerMessage listener, bool autoAck = false)
 {
     _listener = listener;
     _autoAck  = autoAck;
     Connect(_listener, _autoAck);
     CheckStatsAndConnect();
 }
Esempio n. 2
0
        /// <summary>
        /// 持续消费,并检查连接状态并自动恢复
        /// </summary>
        private void Connect(IListenerMessage listener, bool autoAck = false)
        {
            Connect();

            _channel.BasicQos(0, (ushort)_consumeThreadNums, false);
            var consumer = new EventingBasicConsumer(_channel);

            consumer.Received += (model, ea) =>
            {
                bool   result  = true;
                string?message = Encoding.UTF8.GetString(ea.Body.ToArray());
                try
                {
                    listener.Consumer(message, model, ea);
                    _lastAckAt = DateTime.Now;
                }
                catch (AlreadyClosedException e) // rabbit被关闭了,重新打开链接
                {
                    ReStart();
                    //IocCollection.GetService<ILoggerFactory>()
                    //             .CreateLogger(listener.GetType())
                    //             .LogError(e, e.ToString());
                }
                catch (Exception e)
                {
                    // 全局异常处理
                    IocCollection.GetService <IGlobalException>()?.Handle(e, message);
                    // 消费失败后处理
                    //IocCollection.GetService<ILoggerFactory>()
                    //             .CreateLogger(listener.GetType())
                    //             .LogError(e, e.ToString());

                    try
                    {
                        result = listener.FailureHandling(message, model, ea);
                    }
                    catch (Exception exception)
                    {
                        //IocCollection.GetService<ILoggerFactory>()
                        //             .CreateLogger(listener.GetType())
                        //             .LogError(exception, "失败处理出现异常:" + listener.GetType().FullName);
                        result = false;
                    }
                }
                finally
                {
                    if (!autoAck)
                    {
                        if (result)
                        {
                            _channel.BasicAck(ea.DeliveryTag, false);
                        }
                        else
                        {
                            _channel.BasicReject(ea.DeliveryTag, true);
                        }
                    }
                }
            };
            // 消费者开启监听
            _channel.BasicConsume(queue: _queueName, autoAck: autoAck, consumer: consumer);
        }
Esempio n. 3
0
        public ReceiverServiceBase(ILogger logger)
        {
            try
            {
                _logger = logger;
                _logger.WriteInfo(new LogMessage("Init Vecomsoftware.ServiceBus.Receiver"), LogCategories);

                _logger.WriteInfo(new LogMessage("Create new Message Factory"), LogCategories);
                MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ReceiverConfiguration.QueueConnectionString);
                _logger.WriteInfo(new LogMessage(string.Concat("Create new Message Receiver -> ", ReceiverConfiguration.QueueName)), LogCategories);
                MessageReceiver receiver = factory.CreateMessageReceiver(ReceiverConfiguration.QueueName, ReceiveMode.PeekLock);

                _logger.WriteInfo(new LogMessage("Start listening message"), LogCategories);
                AppDomain listenerDomain = Thread.GetDomain();
                listenerDomain.AssemblyResolve += ListenerDomain_AssemblyResolve;
                IWebAPIClient webApiClient = new WebAPIClient(logger, ReceiverConfiguration.AddressesJsonConfigWebAPI);

                _directoryInfo = new DirectoryInfo(Path.Combine(listenerDomain.BaseDirectory, "Listener"));
                _logger.WriteDebug(new LogMessage(string.Concat("DirectoryInfo: ", _directoryInfo.FullName, " (", _directoryInfo.EnumerateFiles().Count(), ")")), LogCategories);
                _logger.WriteDebug(new LogMessage(string.Concat("Searching ... ", ReceiverConfiguration.ListenerAssemblyFullName)), LogCategories);


                Assembly externalAssembly = listenerDomain.Load(File.ReadAllBytes(_directoryInfo.EnumerateFiles()
                                                                                  .Single(f => f.Name.Equals(ReceiverConfiguration.ListenerAssemblyFullName)).FullName));

                Type          currentListener = externalAssembly.GetTypes().Single(f => _type_iListenerMessage.IsAssignableFrom(f));
                bool          containsBiblosDocumentClient = currentListener.GetConstructors().Single().GetParameters().Any(f => f.ParameterType.Equals(_type_biblosClient));
                bool          containsStampaConformeClient = currentListener.GetConstructors().Single().GetParameters().Any(f => f.ParameterType.Equals(_type_stampaConformeClient));
                bool          containsServiceBusClient     = currentListener.GetConstructors().Single().GetParameters().Any(f => f.ParameterType.Equals(_type_serviceBusClient));
                List <object> constructorParameters        = new List <object>
                {
                    receiver,
                    _logger,
                    webApiClient
                };
                if (containsBiblosDocumentClient)
                {
                    constructorParameters.Add(new BiblosDS.BiblosClient());
                }
                if (containsStampaConformeClient)
                {
                    constructorParameters.Add(new StampaConforme.StampaConformeClient());
                }
                if (containsServiceBusClient)
                {
                    constructorParameters.Add(new ServiceBus.ServiceBusClient(logger));
                }
                _listener = (IListenerMessage)Activator.CreateInstance(currentListener, constructorParameters.ToArray());
            }
            catch (ReflectionTypeLoadException r_ex)
            {
                foreach (Exception ex in r_ex.LoaderExceptions)
                {
                    _logger.WriteError(ex, LogCategories);
                }
                throw r_ex;
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex, LogCategories);
                throw ex;
            }
        }