예제 #1
0
        static void Main(string[] args)
        {
            var rabbitOptions = new RabbitOptions
            {
                HostName           = RabbitHostName,
                ExchangeName       = RabbitExchangeName,
                ExchangeAutoDelete = true,
                ExchangeDurable    = false
            };

            var reader    = new RabbitMessageReader(rabbitOptions);
            var converter = new RabbitMessageConverter();
            var source    = new ResourceValidatorSource(typeof(Program).Assembly, "Console.Rabbit.Schemas.{messageType}.json");
            var output    = new ConsoleValidationOutput();

            var monitor = new QueueMonitor(reader, converter, new MessageValidator(source), output);

            monitor.Start();

            var publisher = new Publisher(RabbitHostName, RabbitExchangeName);

            publisher.Start();

            System.Console.WriteLine("Monitoring {0} on {1}.  Press any key to stop.", rabbitOptions.ExchangeName, rabbitOptions.HostName);

            System.Console.ReadKey();
            System.Console.WriteLine("Stopping...");

            publisher.Stop();
            monitor.Stop();
        }
예제 #2
0
 public ConnectionWrapper(
     IConnection connection,
     RabbitOptions options)
 {
     this.connection = connection;
     Options         = options;
 }
        /// <summary>
        /// https://www.c-sharpcorner.com/article/consuming-rabbitmq-messages-in-asp-net-core/
        /// </summary>
        /// <param name="loggerFactory"></param>
        /// <param name="options"></param>
        public MessageConsumerService(ILoggerFactory loggerFactory, IOptions <RabbitOptions> options)
        {
            this._logger  = loggerFactory.CreateLogger <MessageConsumerService>();
            this._options = options?.Value;

            InitRabbitMQ();
        }
예제 #4
0
 public RabbitChannelFactory(IServiceProvider serviceProvider, string providerName)
 {
     this._serviceProvider = serviceProvider;
     this._logger          = serviceProvider.GetRequiredService <ILogger <RabbitChannelFactory> >();
     this.Options          = serviceProvider.GetRequiredService <IOptionsMonitor <RabbitOptions> >().Get(providerName);
     this.RemainderCount   = this.Options.ConnectionPoolCount > 0 ? this.Options.ConnectionPoolCount : 10;
 }
예제 #5
0
        static async Task Main(string[] args)
        {
            var options = new RabbitOptions
            {
                Connection = new RabbitConnection
                {
                    HostName    = "localhost",
                    Username    = "******",
                    Password    = "******",
                    VirtualHost = "/",
                },
                Bindings = GetBindings()
            };

            var manager = new RabbitConnectionManager(new RabbitConnectionFactory(), options);

            var channel = manager.GetChannel();
            var cts     = new CancellationTokenSource();

            channel.Publish("SampleEvents", "SampleEvents", new SampleEvent {
                Id = -101, Greeting = "Mayfair"
            });

            channel.Consume <SampleEvent>(options.Bindings[0].Queue.Queue, true, async se =>
            {
                await Task.CompletedTask;

                cts.Cancel();
            });

            await Task.Delay(-1, cts.Token);
        }
예제 #6
0
 public RabbitPublisherTest()
 {
     Options = new RabbitOptions
     {
         Host  = "localhost",
         Queue = "Test"
     };
 }
 public BatchingRabbitTemplate(
     RabbitOptions options,
     Connection.IConnectionFactory connectionFactory,
     IBatchingStrategy batchingStrategy,
     ILogger logger = null)
     : base(options, connectionFactory, logger)
 {
     _batchingStrategy = batchingStrategy;
 }
예제 #8
0
 public static ConnectionFactory CreateConnectionFactory(this RabbitOptions options)
 => new ConnectionFactory
 {
     HostName    = options.RabbitMqHostName,
     VirtualHost = options.RabbitMqVirtualHost,
     Port        = options.RabbitMqHostPort,
     UserName    = options.RabbitMqUserName,
     Password    = options.RabbitMqPassword
 };
예제 #9
0
파일: Program.cs 프로젝트: matecz/BG
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
 .ConfigureServices((hostContext, services) =>
 {
     IConfiguration configuration = hostContext.Configuration;
     RabbitOptions rabbitOptions  = configuration.GetSection("rabbit").Get <RabbitOptions>();
     services.AddSingleton(rabbitOptions);
     services.AddHostedService <ConsumeRabbitMQHostedService>();
 });
예제 #10
0
 public EventPublisher(IServiceProvider serviceProvider, string providerName)
 {
     this.providerName     = providerName;
     this._serviceProvider = serviceProvider;
     this._logger          = this._serviceProvider.GetRequiredService <ILogger <EventPublisher> >();
     this._options         = serviceProvider.GetRequiredService <IOptionsMonitor <RabbitOptions> >().Get(providerName);
     this._serializer      = this._serviceProvider.GetRequiredServiceByName <ISerializer>(_options.SerializationType);
     this.MaxChannelCount  = this._options.ConnectionPoolCount * 20;//20 channels per connection pool
 }
예제 #11
0
        public RabbitBackgroundReceiver(RabbitServices rabbitService, RabbitEnv rabbitEnv, IServiceCollection collection)
        {
            var provider = collection.BuildServiceProvider();

            _rabbitService = rabbitService;
            _rabbitEnv     = rabbitEnv;
            _logger        = provider.GetRequiredService <ILoggerFactory>().CreateLogger(GetType());
            _options       = provider.GetRequiredService <IOptions <RabbitOptions> >().Value ?? throw new ArgumentNullException(nameof(RabbitOptions));
        }
예제 #12
0
 public BatchingRabbitTemplate(
     RabbitOptions options,
     Connection.IConnectionFactory connectionFactory,
     ISmartMessageConverter messageConverter,
     IBatchingStrategy batchingStrategy,
     ILogger logger = null)
     : base(options, connectionFactory, messageConverter, logger)
 {
     _batchingStrategy = batchingStrategy;
 }
예제 #13
0
        public ConsumeRabbitMQHostedService(ILoggerFactory loggerFactory, RabbitOptions rabbitOptions)
        {
            _rabbitOptions = rabbitOptions;
            _logger        = loggerFactory.CreateLogger <ConsumeRabbitMQHostedService>();

            while (!InitRabbitMq())
            {
            }
            ;
        }
 public DefaultSubscriberService(RabbitOptions rabbitOptions)
 {
     _connectionFactory = new ConnectionFactory()
     {
         UserName    = rabbitOptions.UserName,
         Password    = rabbitOptions.UserName,
         HostName    = rabbitOptions.HostName,
         Port        = rabbitOptions.Port,
         VirtualHost = rabbitOptions.VHost
     };
 }
        public async Task GlobalSetupAsync()
        {
            await Task.Yield();

            var options = new RabbitOptions();

            options.FactoryOptions.Uri         = new Uri("amqp://*****:*****@localhost:5672/");
            options.PoolOptions.MaxConnections = 5;

            ConnectionPool = new ConnectionPool(options);
        }
예제 #16
0
        public MicroserviceTester(RabbitOptions rabbitOptions, params ConsumerOptions[] peopleYouWantToSendMessagesTo)
        {
            CleanUpAfterTest = true;

            _adapter = new RabbitMqAdapter(rabbitOptions.CreateConnectionFactory(), "TestHost");

            Factory = new ConnectionFactory
            {
                HostName    = rabbitOptions.RabbitMqHostName,
                Port        = rabbitOptions.RabbitMqHostPort,
                VirtualHost = rabbitOptions.RabbitMqVirtualHost,
                UserName    = rabbitOptions.RabbitMqUserName,
                Password    = rabbitOptions.RabbitMqPassword
            };

            using (var con = Factory.CreateConnection())
                using (var model = con.CreateModel())
                {
                    //get rid of old exchanges
                    model.ExchangeDelete(rabbitOptions.RabbitMqControlExchangeName);
                    //create a new one
                    model.ExchangeDeclare(rabbitOptions.RabbitMqControlExchangeName, ExchangeType.Topic, true);

                    //setup a sender chanel for each of the consumers you want to test sending messages to
                    foreach (ConsumerOptions consumer in peopleYouWantToSendMessagesTo)
                    {
                        if (!consumer.QueueName.Contains("TEST."))
                        {
                            consumer.QueueName = consumer.QueueName.Insert(0, "TEST.");
                        }

                        var exchangeName = consumer.QueueName.Replace("Queue", "Exchange");

                        //terminate any old queues / exchanges
                        model.ExchangeDelete(exchangeName);
                        model.QueueDelete(consumer.QueueName);
                        _declaredExchanges.Add(exchangeName);

                        //Create a binding between the exchange and the queue
                        model.ExchangeDeclare(exchangeName, ExchangeType.Direct, true); //durable seems to be needed because RabbitMQAdapter wants it?
                        model.QueueDeclare(consumer.QueueName, true, false, false);     //shared with other users
                        model.QueueBind(consumer.QueueName, exchangeName, "");
                        _declaredQueues.Add(consumer.QueueName);

                        //Create a producer which can send to the
                        var producerOptions = new ProducerOptions
                        {
                            ExchangeName = exchangeName
                        };

                        _sendToConsumers.Add(consumer, _adapter.SetupProducer(producerOptions, true));
                    }
                }
        }
 public DefaultConnectionFactoryAccessor(RabbitOptions optionsAcssesor)
 {
     RabbitOptions     = optionsAcssesor;
     ConnectionFactory = new ConnectionFactory()
     {
         UserName    = RabbitOptions.UserName,
         Password    = RabbitOptions.Password,
         VirtualHost = RabbitOptions.VirtualHost,
         HostName    = RabbitOptions.HostName,
         Port        = RabbitOptions.Port,
     };
 }
예제 #18
0
        public RabbitMessageSender(RabbitEnv rabbitEnv, RabbitServices rabbitServices, IServiceCollection services)
        {
            var provider = services.BuildServiceProvider();

            _rabbitEnv         = rabbitEnv;
            _rabbitServices    = rabbitServices;
            _logger            = provider.GetRequiredService <ILoggerFactory>().CreateLogger(GetType());
            _options           = provider.GetRequiredService <IOptions <RabbitOptions> >()?.Value ?? throw new ArgumentNullException(nameof(RabbitOptions));
            _connectionFactory = new ConnectionFactory {
                HostName = _options.Host
            };
        }
예제 #19
0
        public ConnectionPool(RabbitOptions options)
        {
            Guard.AgainstNull(options, nameof(options));
            Options = options;

            _logger = LogHelper.GetLogger <ConnectionPool>();

            _connections       = Channel.CreateBounded <IConnectionHost>(Options.PoolOptions.MaxConnections);
            _connectionFactory = CreateConnectionFactory();

            CreateConnectionsAsync().GetAwaiter().GetResult();
        }
예제 #20
0
        public EventSubscriber(IServiceProvider serviceProvider, string providerName)
        {
            this.providerName           = providerName;
            this._serviceProvider       = serviceProvider;
            this._logger                = this._serviceProvider.GetRequiredService <ILogger <EventSubscriber> >();
            this._options               = serviceProvider.GetRequiredService <IOptionsSnapshot <RabbitOptions> >().Get(providerName);
            this._eventProcessorFactory = serviceProvider.GetRequiredService <IEventProcessorFactory>();
            this._serializer            = this._serviceProvider.GetRequiredServiceByName <ISerializer>(_options.SerializationType);
            var _channelFactory = serviceProvider.GetRequiredServiceByName <IRabbitChannelFactory>(this.providerName);

            this._monitorTimer = new Timer(state => { MonitorConsumer().Wait(); }, null, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10));
        }
예제 #21
0
 public RabbitMQClient(IOptions <RabbitOptions> config)
 {
     options           = config.Value;
     connectionFactory = new ConnectionFactory
     {
         UserName    = options.UserName,
         Password    = options.Password,
         VirtualHost = options.VirtualHost,
         AutomaticRecoveryEnabled = false
     };
     pool = new DefaultObjectPool <ModelWrapper>(new ModelPooledObjectPolicy(connectionFactory, options));
 }
예제 #22
0
 public RabbitConnection(IServiceProvider serviceProvider, RabbitOptions options)
 {
     this._serviceProvider   = serviceProvider;
     this.Options            = options;
     this._connectionFactory = new ConnectionFactory
     {
         UserName    = this.Options.UserName,
         Password    = this.Options.Password,
         VirtualHost = this.Options.VirtualHost,
         AutomaticRecoveryEnabled = false
     };
     this.Connection = this._connectionFactory.CreateConnection(this.Options.EndPoints);
 }
        public static IServiceCollection AddRabbit(this IServiceCollection services, IConfiguration configuration, RabbitOptions rabbitConfig)
        {
            services.Configure <RabbitOptions>((x) =>
            {
                x = rabbitConfig;
            });

            services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();
            services.AddSingleton <IPooledObjectPolicy <IModel>, RabbitModelPooledObjectPolicy>(x => new RabbitModelPooledObjectPolicy(rabbitConfig));

            services.AddSingleton <IRabbitManager, RabbitManager>();

            return(services);
        }
예제 #24
0
        public DefaultSubscribeClient(IServiceProvider serviceProvider
                                      , IConnectionFactoryAccessor connectionFactoryAccessor
                                      , RabbitOptions rabbitOptions
                                      , string group
                                      , string exchange)
        {
            _serviceProvider           = serviceProvider;
            _connectionFactoryAccessor = connectionFactoryAccessor;
            _rabbitOptions             = rabbitOptions;
            _group    = group;
            _exchange = exchange;

            _logger = _serviceProvider.GetService <ILogger <DefaultSubscribeClient> >();
        }
예제 #25
0
        public static IServiceCollection AddRabbit(this IServiceCollection services, Action <RabbitOptions> action)
        {
            var options = new RabbitOptions();

            action.Invoke(options);

            services.AddSingleton <IRabbitConnectionFactory, RabbitConnectionFactory>();
            services.AddSingleton(options);

            //var manager = new RabbitConnectionManager(new RabbitConnectionFactory(), options);
            services.AddSingleton <IRabbitConnectionManager, RabbitConnectionManager>();
            services.AddSingleton <IRabbitChannelFactory, RabbitChannelFactory>();

            return(services);
        }
예제 #26
0
 public RabbitService(
     RabbitOptions options,
     ISerializationProvider serializationProvider,
     IEncryptionProvider encryptionProvider   = null,
     ICompressionProvider compressionProvider = null,
     ILoggerFactory loggerFactory             = null,
     Func <IPublishReceipt, ValueTask> processReceiptAsync = null) : this(
         new ChannelPool(options),
         serializationProvider,
         encryptionProvider,
         compressionProvider,
         loggerFactory,
         processReceiptAsync)
 {
 }
예제 #27
0
        public void ConfigureServices(IServiceCollection services)
        {
            //services.Configure<RabbitOptions>(Configuration.GetSection("RabbitMqConnection"));

            var rabbitOptions = new RabbitOptions();

            Configuration.GetSection("RabbitMqConnection").Bind(rabbitOptions);

            services.AddSingleton <IRabbitPublisher, DefaultPublisherService>(serviceProvider =>
            {
                return(new DefaultPublisherService(rabbitOptions));
            });

            services.AddControllers();
        }
예제 #28
0
        public void AddServices(IServiceCollection serviceCollection)
        {
            var options = new RabbitOptions();

            _configure(options);

            var envConcator = serviceCollection.BuildServiceProvider().GetRequiredService <IEnviromentNameConcator>();

            options.DefaultDeadLetterExchange      = envConcator.Concat(options.DefaultDeadLetterExchange);
            options.DefaultFinalDeadLetterExchange = envConcator.Concat(options.DefaultFinalDeadLetterExchange);
            options.DefaultExchangeName            = envConcator.Concat(options.DefaultExchangeName);

            serviceCollection.AddSingleton(options);
            serviceCollection.AddScoped <IMessageQueueTransaction, MessageQueueTransaction>();
        }
        public RabbitMessageChannelBinder(IApplicationContext context, ILogger <RabbitMessageChannelBinder> logger, SteeltoeConnectionFactory connectionFactory, RabbitOptions rabbitOptions, RabbitBinderOptions binderOptions, RabbitBindingsOptions bindingsOptions, RabbitExchangeQueueProvisioner provisioningProvider, IListenerContainerCustomizer containerCustomizer, IMessageSourceCustomizer sourceCustomizer)
            : base(context, Array.Empty <string>(), provisioningProvider, containerCustomizer, sourceCustomizer, logger)
        {
            if (connectionFactory == null)
            {
                throw new ArgumentNullException(nameof(connectionFactory));
            }

            if (rabbitOptions == null)
            {
                throw new ArgumentNullException(nameof(rabbitOptions));
            }

            _logger                 = logger;
            ConnectionFactory       = connectionFactory;
            RabbitConnectionOptions = rabbitOptions;
            BinderOptions           = binderOptions;
            BindingsOptions         = bindingsOptions;
            ServiceName             = "rabbitBinder";
        }
예제 #30
0
        public static void Main(string[] args)
        {
            Configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.RabbitMq.json", optional: false, reloadOnChange: true)
                            .AddCommandLine(args)
                            .Build();

            var rabbitOptions = new RabbitOptions();

            Configuration.GetSection("RabbitMqConnection").Bind(rabbitOptions);
            var subscriber = new DefaultSubscriberService(rabbitOptions);

            var messageHandler         = new RabbitMessageHandler();
            var messagingConfiguration = new MessagingConfiguration(exchangeName: "WeatherForecastExchange", queueName: "WeatherForecast-Queue");

            subscriber.Consume(messagingConfiguration, messageHandler);

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }