示例#1
0
        private async Task <ProducerResult> SendAsync(Messages <byte[]> messages)
        {
            IModel       channel = null;
            IChannelPool pool    = null;

            try
            {
                GenerateChannel(messages, ref channel, ref pool, out IBasicProperties props, out string exchage, out string routingKey);

                // 发送消息
                foreach (var item in messages.Body)
                {
                    channel.BasicPublish(exchage, routingKey, props, item);
                }
                _logger.LogDebug($"RabbitMQ message [{exchage}-{routingKey}] has been published.");

                return(ProducerResult.Success);
            }
            catch (Exception ex)
            {
                return(ExceptionReturn(await _serializer.SerializeMessageToStringAsync(messages), pool?.HostAddress, ex));
            }
            finally
            {
                Dispose(channel, pool);
            }
        }
示例#2
0
        public async Task <bool> PurgeQueueAsync(
            IChannelPool channelPool,
            string queueName,
            bool deleteQueueAfter = false)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));
            Guard.AgainstNullOrEmpty(queueName, nameof(queueName));

            var error       = false;
            var channelHost = await channelPool.GetChannelAsync().ConfigureAwait(false);

            try
            {
                channelHost.GetChannel().QueuePurge(queueName);

                if (deleteQueueAfter)
                {
                    channelHost.GetChannel().QueueDelete(queueName, false, false);
                }
            }
            catch { error = true; }
            finally
            {
                await channelPool
                .ReturnChannelAsync(channelHost, error);
            }

            return(error);
        }
示例#3
0
        public Publisher(IChannelPool channelPool, ReadOnlyMemory <byte> hashKey)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));

            Config  = channelPool.Config;
            _logger = LogHelper.GetLogger <Publisher>();

            if (Config.PublisherSettings.Encrypt && hashKey.Length != Utils.Constants.EncryptionKeySize)
            {
                _encrypt = false;
                _logger.LogWarning("Encryption disabled, invalid hash key length ({0}) provided. Expected key length of {1}.", hashKey.Length, Utils.Constants.EncryptionKeySize);
            }
            else if (Config.PublisherSettings.Encrypt)
            {
                _encrypt = true;
                _hashKey = hashKey;
            }

            _channelPool   = channelPool;
            _receiptBuffer = Channel.CreateUnbounded <PublishReceipt>(
                new UnboundedChannelOptions
            {
                SingleWriter = false,
                SingleReader = true,
            });

            _withHeaders           = Config.PublisherSettings.WithHeaders;
            _createPublishReceipts = Config.PublisherSettings.CreatePublishReceipts;
            _compress            = Config.PublisherSettings.Compress;
            _waitForConfirmation = TimeSpan.FromMilliseconds(Config.PublisherSettings.WaitForConfirmationTimeoutInMilliseconds);
        }
示例#4
0
        public Topologer(IChannelPool channelPool)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));

            Options      = channelPool.Options;
            _channelPool = channelPool;
        }
示例#5
0
        public async Task <bool> TransferMessageAsync(
            IChannelPool channelPool,
            string originQueueName,
            string targetQueueName)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));
            Guard.AgainstNullOrEmpty(originQueueName, nameof(originQueueName));
            Guard.AgainstNullOrEmpty(targetQueueName, nameof(targetQueueName));

            var error       = false;
            var channelHost = await channelPool.GetChannelAsync().ConfigureAwait(false);

            var properties = channelHost.GetChannel().CreateBasicProperties();

            properties.DeliveryMode = 2;

            try
            {
                var result = channelHost.GetChannel().BasicGet(originQueueName, true);

                if (result?.Body != null)
                {
                    channelHost.GetChannel().BasicPublish(string.Empty, targetQueueName, false, properties, result.Body);
                }
            }
            catch { error = true; }
            finally
            {
                await channelPool
                .ReturnChannelAsync(channelHost, error);
            }

            return(error);
        }
示例#6
0
        public RabbitService(
            IChannelPool chanPool,
            ISerializationProvider serializationProvider,
            IEncryptionProvider encryptionProvider   = null,
            ICompressionProvider compressionProvider = null,
            ILoggerFactory loggerFactory             = null,
            Func <IPublishReceipt, ValueTask> processReceiptAsync = null)
        {
            Guard.AgainstNull(chanPool, nameof(chanPool));
            Guard.AgainstNull(serializationProvider, nameof(serializationProvider));
            LogHelper.LoggerFactory = loggerFactory;

            Options     = chanPool.Options;
            ChannelPool = chanPool;

            SerializationProvider = serializationProvider;
            EncryptionProvider    = encryptionProvider;
            CompressionProvider   = compressionProvider;

            Publisher = new Publisher(ChannelPool, SerializationProvider, EncryptionProvider, CompressionProvider);
            Topologer = new Topologer(ChannelPool);

            Options.ApplyGlobalConsumerOptions();
            BuildConsumers();

            Publisher.StartAutoPublish(processReceiptAsync);

            BuildConsumerTopologyAsync()
            .GetAwaiter()
            .GetResult();
        }
        public RabbitMQSubscribeMiddleware(
            IChannelPool channelPool,
            IRabbitMqSerializer serializer)
        {
            this.serializer  = serializer;
            this.channelPool = channelPool;

            ChannelAccessor = channelPool.Acquire(ChannelQueueName, ConnectionName);


            QueueDeclareConfiguration QueueConfiguration = new QueueDeclareConfiguration(ChannelQueueName);

            QueueConfiguration.Declare(ChannelAccessor.Channel);

            var properties = ChannelAccessor.Channel.CreateBasicProperties();

            properties.Persistent = true;



            Consumer           = new EventingBasicConsumer(ChannelAccessor.Channel);
            Consumer.Received += (model, ea) =>
            {
                var    body    = ea.Body.ToArray();
                string message = (string)serializer.Deserialize(ea.Body.ToArray(), typeof(string));
                Console.WriteLine(" [Subscribe] Received {0}", string.Format(message, DateTime.Now));
                ChannelAccessor.Channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
            };

            ChannelAccessor.Channel.BasicConsume(
                queue: QueueConfiguration.QueueName,
                autoAck: false,
                consumer: Consumer
                );
        }
示例#8
0
        public Topologer(Config config)
        {
            Guard.AgainstNull(config, nameof(config));

            Config       = config;
            _channelPool = new ChannelPool(Config);
        }
 public RabbitMqDistributedEventBus(
     IConsumerFactory consumerFactory,
     IRabbitMqSerializer serializer,
     IEventBusSubscriptionsManager subscriptionsManager,
     IServiceProvider serviceProvider,
     IChannelPool channelPool,
     IOptions <EventBusOptions> eventBusOptions,
     IOptions <RabbitMqEventBusOptions> rabbitMOptions)
     : base(subscriptionsManager, serviceProvider, eventBusOptions)
 {
     RabbitMqOptions = rabbitMOptions.Value;
     ConsumerFactory = consumerFactory;
     Serializer      = serializer;
     ChannelPool     = channelPool;
     ChannelAccessor = ChannelPool.Acquire();
     Consumer        = ConsumerFactory.Create(
         new ExchangeDeclareConfiguration(
             RabbitMqOptions.Exchange,
             type: "direct",
             durable: true),
         new QueueDeclareConfiguration(
             RabbitMqOptions.QueueName,
             durable: true,
             exclusive: false,
             autoDelete: false),
         RabbitMqOptions.ConnectionName
         );
     Consumer.OnMessageReceived(ProcessEventAsync);
     _subsManager.OnEventRemoved += SubsManager_OnEventRemoved;
 }
示例#10
0
        public Topologer(IChannelPool channelPool)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));

            Config       = channelPool.Config;
            _channelPool = channelPool;
        }
 public RabbitMQPublishMiddleware(
     IChannelPool channelPool,
     IRabbitMqSerializer serializer)
 {
     this.serializer  = serializer;
     this.channelPool = channelPool;
     ChannelAccessor  = channelPool.Acquire(ChannelQueueName, ConnectionName);
 }
示例#12
0
 public bool TryGetValue(string name, out IChannelPool value)
 {
     if (!_pools.TryGetValue(name, out value))
     {
         throw new ChannelPoolNotFoundException(name);
     }
     return(true);
 }
示例#13
0
 public Consumer(IChannelPool channelPool, string consumerName)
     : this(
         channelPool,
         channelPool.Options.GetConsumerOptions(consumerName))
 {
     Guard.AgainstNull(channelPool, nameof(channelPool));
     Guard.AgainstNullOrEmpty(consumerName, nameof(consumerName));
 }
示例#14
0
        public Publisher(IChannelPool channelPool)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));

            _logger       = LogHelper.GetLogger <Publisher>();
            _channelPool  = channelPool;
            Config        = channelPool.Config;
            ReceiptBuffer = Channel.CreateUnbounded <PublishReceipt>();
        }
示例#15
0
        public Publisher(Config config)
        {
            Guard.AgainstNull(config, nameof(config));

            _logger       = LogHelper.GetLogger <Publisher>();
            _channelPool  = new ChannelPool(Config);
            Config        = config;
            ReceiptBuffer = Channel.CreateUnbounded <PublishReceipt>();
        }
示例#16
0
        public ConsumerTests(ITestOutputHelper output)
        {
            this.output = output;
            config      = ConfigReader.ConfigFileReadAsync("TestConfig.json").GetAwaiter().GetResult();

            channelPool   = new ChannelPool(config);
            topologer     = new Topologer(config);
            rabbitService = new RabbitService("Config.json", null, null, null, null);
        }
示例#17
0
 public RabbitMqDistributedEventBus(
     IOptions <RabbitMqDistributedEventBusOptions> options,
     IChannelPool channelPool,
     IRabbitMqSerializer serializer)
 {
     ChannelPool = channelPool;
     Serializer  = serializer;
     Options     = options.Value;
 }
示例#18
0
 public EventSubscriber(
     IChannelPool channelPool,
     HandlersStorage handlersStorage,
     MiddlewaresStorage middlewaresStorage,
     IServiceScopeFactory serviceScopeFactory,
     ILogger <EventSubscriber> logger) : base(channelPool, handlersStorage, middlewaresStorage, serviceScopeFactory)
 {
     _logger = logger;
 }
示例#19
0
        public AutoPublisher(IChannelPool channelPool, bool withHeaders = true)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));

            _logger      = LogHelper.GetLogger <AutoPublisher>();
            Config       = channelPool.Config;
            Publisher    = new Publisher(channelPool);
            _withHeaders = withHeaders;
        }
示例#20
0
        public ConsumerTests(ITestOutputHelper output)
        {
            this.output = output;
            options     = JsonFileReader.ReadFileAsync <Options>("TestConfig.json").GetAwaiter().GetResult();

            channelPool   = new ChannelPool(options);
            topologer     = new Topologer(options);
            rabbitService = new RabbitService("Config.json", null, null, null, null);
        }
 public MessageBus(
     IChannelPool channelPool,
     ILogger <MessageBus> logger,
     IMessageStorage storage = null)
 {
     _channelPool = channelPool;
     _logger      = logger;
     _storage     = storage;
 }
        public async Task <bool> TransferAllMessagesAsync(
            IChannelPool originChannelPool,
            IChannelPool targetChannelPool,
            string originQueueName,
            string targetQueueName)
        {
            Guard.AgainstNull(originChannelPool, nameof(originChannelPool));
            Guard.AgainstNull(targetChannelPool, nameof(targetChannelPool));
            Guard.AgainstNullOrEmpty(originQueueName, nameof(originQueueName));
            Guard.AgainstNullOrEmpty(targetQueueName, nameof(targetQueueName));

            var error       = false;
            var channelHost = await originChannelPool.GetChannelAsync().ConfigureAwait(false);

            var properties = channelHost.Channel.CreateBasicProperties();

            properties.DeliveryMode = 2;

            BasicGetResult result = null;

            while (true)
            {
                try
                {
                    result = channelHost.Channel.BasicGet(originQueueName, true);
                    if (result == null)
                    {
                        break;
                    }
                }
                catch { error = true; }
                finally
                {
                    await originChannelPool
                    .ReturnChannelAsync(channelHost, error);
                }

                if (!error && result?.Body != null)
                {
                    try
                    {
                        var targetChannelHost = await targetChannelPool.GetChannelAsync().ConfigureAwait(false);

                        targetChannelHost.Channel.BasicPublish(string.Empty, targetQueueName, false, properties, result.Body);
                    }
                    catch { error = true; }
                    finally
                    {
                        await targetChannelPool
                        .ReturnChannelAsync(channelHost, error);
                    }
                }
            }

            return(error);
        }
示例#23
0
        public Consumer(IChannelPool channelPool, ConsumerOptions consumerOptions)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));
            Guard.AgainstNull(consumerOptions, nameof(consumerOptions));

            _logger         = LogHelper.GetLogger <Consumer>();
            Options         = channelPool.Options;
            ChannelPool     = channelPool;
            ConsumerOptions = consumerOptions;
        }
 public RabbitBasicDemo(
     IChannelPool channelPool,
     IRabbitMqSerializer serializer,
     ILogger <RabbitBasicDemo> logger)
 {
     _logger          = logger;
     this.serializer  = serializer;
     this.channelPool = channelPool;
     ChannelAccessor  = channelPool.Acquire(ChannelQueueName, ConnectionName);
 }
示例#25
0
        /// <summary>
        /// Use this constructor with DependencyInjection. Config's values are only used for RabbitService-esque settings and for building of Consumers.
        /// </summary>
        /// <param name="config"></param>
        /// <param name="channelPool"></param>
        /// <param name="autoPublisher"></param>
        /// <param name="toploger"></param>
        /// <param name="loggerFactory"></param>
        public RabbitService(Config config, IChannelPool channelPool, IAutoPublisher autoPublisher, ITopologer toploger, ILoggerFactory loggerFactory = null)
        {
            LogHelper.LoggerFactory = loggerFactory;

            Config        = config;
            ChannelPool   = channelPool;
            AutoPublisher = autoPublisher;
            Topologer     = toploger;

            BuildConsumers();
        }
示例#26
0
        public Consumer(IChannelPool channelPool, ConsumerOptions consumerSettings, byte[] hashKey = null)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));
            Guard.AgainstNull(consumerSettings, nameof(consumerSettings));

            _logger          = LogHelper.GetLogger <Consumer>();
            Config           = channelPool.Config;
            ChannelPool      = channelPool;
            HashKey          = hashKey;
            ConsumerSettings = consumerSettings;
        }
        public void StartInitialization()
        {
            ILoggerFactory connectionLoggerFactory = LoggerFactory.Create("");
            IRmqLogger     connectionLogger        = connectionLoggerFactory.CreateLogger(nameof(ConnectionWrapper));

            connection = new ConnectionWrapper(config, connectionLogger);

            IModel rpcCh = connection.CreateChannel();


            rpcChannelPool = channelPoolFactory.CreateChannelPool(rpcCh);

            IConsumerBinder  rpcConsumerBinder  = new RpcConsumerBinder();
            IConsumerFactory rpcConsumerFactory = new ConsumerFactory(
                rpcChannelPool.GetChannelWrapper(),
                rpcConsumerBinder);

            ILoggerFactory loggerFactory = LoggerFactory.Create(ConsumerType.Rpc.ToString());
            IRmqLogger     managerLogger = loggerFactory.CreateLogger(nameof(ConsumerManager));

            IConsumerManager rpcConsumerManager = new ConsumerManager(
                rpcConsumerFactory,
                managerLogger);

            rpcConsumerManager.InitConsumer();


            IMainConsumerEventHandlerFactory rpcMainEventHandlerFactory
                = ConsumerEventHandlersFactory.Create(rpcConsumerManager, loggerFactory);

            IConsumerMainEventHandlers rpcConsumerMainEventHandler
                = rpcMainEventHandlerFactory.CreateMainHandler();



            IRmqLogger connectionHandlerLogger = loggerFactory.CreateLogger(nameof(ConnectionEventHandlers));
            IConnectionEventsHandlerFactory connectionEventsHandlerFactory
                = ConnectionEventsHandlerFactory.Create(connectionHandlerLogger, connection);
            IConnectionEventHandlers connectionEventHandler = connectionEventsHandlerFactory.CreateHandler();


            IRmqLogger channelGuardLogger = loggerFactory.CreateLogger(nameof(ChannelGuardService));

            this.channelGuardService
                = new ChannelGuardService(
                      rpcChannelPool,                   // <--- TODO только rpc?
                      channelGuardLogger,
                      connectionEventHandler,
                      rpcConsumerMainEventHandler);

            // Подписка на ответы запросов rpc
            responseMessageHandler = responseMessageHandlerFactory.GetHandler();
            rpcConsumerMainEventHandler.AddReceiveHandler(responseMessageHandler.HandleMessage);
        }
示例#28
0
        public AutoPublisherTests(ITestOutputHelper output)
        {
            this.output = output;
            options     = new Options();
            options.FactoryOptions.Uri = new Uri("amqp://*****:*****@localhost:5672/");
            options.PublisherOptions   = new PublisherOptions();
            options.PublisherOptions.CreatePublishReceipts = true;

            channelPool = new ChannelPool(options);

            topologer = new Topologer(channelPool);
        }
示例#29
0
        public AutoPublisherTests(ITestOutputHelper output)
        {
            this.output = output;
            config      = new Config();
            config.FactorySettings.Uri = new Uri("amqp://*****:*****@localhost:5672/");
            config.PublisherSettings   = new PublisherOptions();
            config.PublisherSettings.CreatePublishReceipts = true;

            channelPool = new ChannelPool(config);

            topologer = new Topologer(channelPool);
        }
示例#30
0
        public Consumer(IChannelPool channelPool, string consumerName, byte[] hashKey = null)
        {
            Guard.AgainstNull(channelPool, nameof(channelPool));
            Guard.AgainstNullOrEmpty(consumerName, nameof(consumerName));

            _logger     = LogHelper.GetLogger <Consumer>();
            Config      = channelPool.Config;
            ChannelPool = channelPool;
            HashKey     = hashKey;

            ConsumerSettings = Config.GetConsumerSettings(consumerName);
        }