示例#1
0
        public RabbitMqListenerService(IRabbitMqConfig config, int retryCount, IMessageCoordinator messageCoordinator)
        {
            this.config             = config;
            this.messageCoordinator = messageCoordinator;

            ConnectAndListen(retryCount);
        }
示例#2
0
        /// <summary>
        /// Sets the <see cref="IRabbitMqConfig"/> for the registered <see cref="RabbitMqService{T}"/>.
        /// </summary>
        public RabbitMqServiceBuilder <T> WithRabbitMqConfig(IRabbitMqConfig rabbitMqConfig)
        {
            // make sure that we are not using the same IRabbitMqConfig instance as the argument
            // ReSharper disable once ConstantConditionalAccessQualifier
            _configRabbitMqConfig = rabbitMqConfig?.Copy ?? new RabbitMqConfig();

            return(this);
        }
示例#3
0
        public RabbitMqRpcService(IRabbitMqConfig config, ILogger <RabbitMqRpcService> logger)
        {
            this.config     = config;
            this.logger     = logger;
            pendingMessages = new ConcurrentDictionary <Guid, TaskCompletionSource <IMessageContract> >();

            ConnectAndListen();
        }
示例#4
0
        /// <summary>
        /// Create new instance of <see cref="IConsumeManager"/>.
        /// </summary>
        /// <param name="configureAction">Initiation method.</param>
        /// <param name="config">Rabbit connection attributes.</param>
        public static IConsumeManager Create(IRabbitMqConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            var mngr = new ConsumeManager(config);

            return(mngr);
        }
        /// <summary>
        /// This static method is used by <see cref="RabbitMqServiceBuilder{T}"/> to construct a singleton hosted service
        /// for a consumer of a producer.
        ///
        /// Its purpose is to instantiate the <c>TDerived</c>, passing in the <see cref="IServiceProvider"/> argument.
        ///
        /// The services that can be injected this way are the ones that have been registered up to the call site of
        /// <see cref="Create{TDerived}"/>.
        /// </summary>
        /// <param name="isConsumer"/>
        /// <param name="busProxy"/>
        /// <param name="rmqConfig"/>
        /// <param name="onConnected"/>
        /// <param name="serviceProvider"/>
        /// <typeparam name="TDerived">
        /// The type of the consumer or producer that is being instantiated. It must match type parameter <c>T</c> of
        /// type <see cref="RabbitMqService{T}"/>.
        /// </typeparam>
        /// <returns>
        /// An instantiated <see cref="RabbitMqService{TDerived}"/> which should be used to register a consumer or
        /// producer as a singleton hosted service.
        /// </returns>
        public static TDerived Create <TDerived>(
            bool isConsumer,
            IBusProxy busProxy,
            IRabbitMqConfig rmqConfig,
            List <OnConnectedCallback> onConnected,
            IServiceProvider serviceProvider)
            where TDerived : RabbitMqService <TDerived>
        {
            // ReSharper disable once ConstantConditionalAccessQualifier
            Debug.Assert(busProxy?.Bus != null, $"{nameof(IBusProxy.Bus)} must not be null.");

            Debug.Assert(rmqConfig != null, $"{nameof(IRabbitMqConfig)} must not be null.");

            var logger = serviceProvider.GetService <ILogger <TDerived> >();

            TDerived service;

            try
            {
                service = ActivatorUtilities.CreateInstance <TDerived>(serviceProvider);
            }
            catch (Exception)
            {
                // ReSharper disable once ConstantConditionalAccessQualifier
                logger?.LogCritical(
                    $"Could not instantiate a {typeof(TDerived).Name} in {nameof(RabbitMqService<T>)}." +
                    $"{nameof(Create)}.");

                throw;
            }

            service._isConsumer = isConsumer;

            service.IncomingMessageInterceptor =
                serviceProvider.GetService <IIncomingMessageInterceptor <T> >() ??
                serviceProvider.GetService <IIncomingMessageInterceptor>();

            service.OutgoingMessageInterceptor =
                serviceProvider.GetService <IOutgoingMessageInterceptor <T> >() ??
                serviceProvider.GetService <IOutgoingMessageInterceptor>();

            service._busProxy              = busProxy;
            service._rmqConfig             = rmqConfig;
            service._onConnected           = onConnected;
            service._logger                = logger;
            service._isProperlyInitialized = true;

            service.Initialize();

            return(service);
        }
        /// <summary>
        /// This static method is used by <see cref="RabbitMqServiceBuilder{T}"/> to construct a singleton hosted
        /// service for a consumer of a producer.
        ///
        /// Its purpose is to be used with <see cref="RabbitMqServiceBuilder{T}"/> so as to allow reuse of
        /// <see cref="IAdvancedBus"/> singletons
        ///
        /// This is done in order to enable the use of the same or different connections to the RabbitMQ server, on
        /// demand.
        ///
        /// For more information about how <see cref="IAdvancedBus"/> instances can be reused, see
        /// <see cref="RabbitMqServiceBuilder{T}"/>.
        /// </summary>
        /// <param name="rmqConfig"/>
        /// <param name="useStronglyTypedMessages"/>
        /// <param name="useCorrelationIds"/>
        /// <param name="serviceProvider"/>
        /// <returns/>
        public static Lazy <IAdvancedBus> CreateLazyBus(
            IRabbitMqConfig rmqConfig,
            bool useStronglyTypedMessages,
            bool useCorrelationIds,
            IServiceProvider serviceProvider) =>
        new Lazy <IAdvancedBus>(() => RabbitHutch.CreateBus(new ConnectionConfiguration
        {
            Hosts = new List <HostConfiguration>
            {
                new HostConfiguration
                {
                    Host = rmqConfig.HostName,
                    Port = rmqConfig.Port
                }
            },
            Name                   = rmqConfig.Id,
            UserName               = rmqConfig.UserName,
            Password               = rmqConfig.Password,
            Product                = nameof(RabbitMqService <T>),
            RequestedHeartbeat     = rmqConfig.RequestedHeartbeat,
            PersistentMessages     = rmqConfig.PersistentMessages,
            PublisherConfirms      = rmqConfig.PublisherConfirms,
            Timeout                = rmqConfig.MessageDeliveryTimeout,
            ConnectIntervalAttempt = rmqConfig.ReconnectionAttemptInterval,
        }, container =>
        {
            container.Register(serviceProvider);

            container.Register <IConsumerErrorStrategy, ConsumerErrorStrategy>();

            container.Register <IMessageSerializationStrategy>(serviceResolver =>
            {
                var serializer = serviceResolver.Resolve <ISerializer>();
                var correlationIdGenerationStrategy = serviceResolver.Resolve <ICorrelationIdGenerationStrategy>();

                if (useStronglyTypedMessages)
                {
                    var typeNameSerializer = serviceResolver.Resolve <ITypeNameSerializer>();

                    return(new TypedMessageSerializationStrategy(
                               useCorrelationIds, typeNameSerializer, serializer, correlationIdGenerationStrategy));
                }

                return(new UntypedMessageSerializationStrategy(
                           useCorrelationIds, serializer, correlationIdGenerationStrategy));
            });
        }).Advanced);
示例#7
0
        public void Initialise(IRabbitMqConfig config)
        {
            _logger.LogTrace(LoggingEvents.Initialise, "Initialising provider");

            try
            {
                var builder = _serviceProvider.GetRequiredService <IPipelineBuilder>();
                config.ConfigurePipeline(builder);
                _pipeline = builder.Build();
            }
            catch (Exception ex)
            {
                // Exception during pipeline building - likely due to missing IoC wire up

                _logger.LogError(
                    LoggingEvents.InitialiseError,
                    ex,
                    "Initialisation error"
                    );

                // No recovery possible.
                throw;
            }
        }
示例#8
0
 private ConsumeManager(IRabbitMqConfig config)
 {
     _rabbitSettings = config;
 }
示例#9
0
        public static PublishService Create(IRabbitMqConfig settings)
        {
            var srv = new PublishService(settings);

            return(srv);
        }
示例#10
0
 private PublishService(IRabbitMqConfig config)
 {
     _rabbitSettings = config;
 }
 public RabbitMqCommandHandlerBase(IRabbitMqConfig config)
 {
     this.config = config;
 }
示例#12
0
 public ConnectionFactory(IRabbitMqConfig config)
 {
     _config = config;
 }
        /// <summary>
        /// Builds a <see cref="ServiceDescriptor"/>, describing a singleton <see cref="IHostedService"/>, to be used
        /// with dependency injection.
        /// </summary>
        /// <remarks>
        /// It reuses an existing <see cref="IBusProxy"/> singleton, if one is found using the provided
        /// <see cref="IRabbitMqConfig.Id"/>.
        ///
        /// If not, a new <see cref="IBusProxy"/> singleton is registered in the service factory wrapped by the
        /// <see cref="ServiceDescriptor"/>.
        /// </remarks>
        public Func <IServiceProvider, T> Build(IServiceCollection serviceCollection)
        {
            var isConsumer = typeof(T).IsSubclassOf(typeof(RabbitMqConsumer <T>));

            if (!isConsumer && !typeof(T).IsSubclassOf(typeof(RabbitMqProducer <T>)))
            {
                throw new Exception(
                          $"{nameof(T)}, of type {typeof(T).FullName}, must be a subclass of " +
                          $"{nameof(RabbitMqConsumer<T>)} or {nameof(RabbitMqProducer<T>)}.");
            }

            if (_configRabbitMqConfig == null)
            {
                _configRabbitMqConfig = new RabbitMqConfig();
            }

            var busProxy = serviceCollection
                           .Where(serviceDescriptor =>
                                  serviceDescriptor.Lifetime == ServiceLifetime.Singleton &&
                                  serviceDescriptor.ServiceType == typeof(IBusProxy))
                           .Select(serviceDescriptor => (IBusProxy)serviceDescriptor.ImplementationInstance)
                           .FirstOrDefault(registeredBusProxy => registeredBusProxy.Id == _configRabbitMqConfig.Id);

            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
            // ReSharper disable HeuristicUnreachableCode
            if (busProxy == null)
            {
                // build an IServiceProvider early so as to ensure that an ILogger<T> can be passed to
                // ConsumerErrorStrategy
                var serviceProvider =
                    new DefaultServiceProviderFactory(new ServiceProviderOptions
                {
                    ValidateScopes = false
                })
                    .CreateBuilder(serviceCollection)
                    .BuildServiceProvider();

                var bus = RabbitMqService <T> .CreateLazyBus(
                    _configRabbitMqConfig, _configUseStronglyTypedMessages, _configUseCorrelationIds, serviceProvider);

                busProxy = new BusProxy(_configRabbitMqConfig.Id, bus);

                serviceCollection.AddSingleton(busProxy);
            }
            // ReSharper restore HeuristicUnreachableCode

            Func <IServiceProvider, T> BuildServiceFactoryFactory()
            {
                T   service = null;
                var @lock   = new object();

                return(serviceProvider =>
                {
                    // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                    if (service != null)
                    {
                        return service;
                    }

                    lock (@lock)
                    {
                        if (service != null)
                        {
                            return service;
                        }

                        // _configRabbitMqConfig must not be null here
                        service = RabbitMqService <T> .Create <T>(
                            isConsumer, busProxy, _configRabbitMqConfig, _configOnConnected, serviceProvider);

                        return service;
                    }
                });
            }

            return(BuildServiceFactoryFactory());
        }
示例#14
0
 public RabbitMqCommandHandler(IRabbitMqConfig config) : base(config)
 {
 }
示例#15
0
 public RabbitMqSubscriber(IRabbitMqConfig config)
 {
     this.config = config;
 }
示例#16
0
 private static IRabbitMqListenerService InitializeListenerService(IRabbitMqConfig config, int retries)
 {
     return(new RabbitMqListenerService(config, retries, CreateMessageCoordinator()));
 }