Exemplo n.º 1
0
    public static IApplicationBuilder UseRabbitMq(this IApplicationBuilder applicationBuilder,
                                                  string subscriptionIdPrefix = null, Assembly consumerAssembly = null)
    {
        consumerAssembly ??= Assembly.GetEntryAssembly();

        if (consumerAssembly is null)
        {
            throw new ArgumentNullException(nameof(consumerAssembly));
        }

        var services = applicationBuilder.ApplicationServices;

        var lifeTime           = services.GetService <IApplicationLifetime>();
        var rabbitMqConnection = services.GetService <IRabbitMqConnection>();

        lifeTime.ApplicationStarted.Register(() =>
        {
            var subscriber = new AutoSubscriber(rabbitMqConnection.Bus, subscriptionIdPrefix)
            {
                AutoSubscriberMessageDispatcher =
                    new MicrosoftDependencyInjectionMessageDispatcher(applicationBuilder.ApplicationServices)
            };

            subscriber.Subscribe(new[] { consumerAssembly });
            subscriber.SubscribeAsync(new[] { consumerAssembly });
        });

        lifeTime.ApplicationStopped.Register(() => rabbitMqConnection.Bus.Dispose());

        return(applicationBuilder);
    }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            var connStr = "host=127.0.0.1;virtualHost=wangyunfei;username=admin;password=admin";


            /*
             * 过IBus实例去订阅消息(这里是除非用户关闭程序否则一直处于监听状态),
             * 当发布者发布了指定类型的消息之后,这里就把它打印出来(红色字体显示)。
             */
            using (var bus = RabbitHutch.CreateBus(connStr))
            {
                //This is something you only should do ONCE, preferably on application start up.
                AutoSubscriber autoSubscriber = new AutoSubscriber(bus, "WYF");
                //autoSubscriber.Subscribe(Assembly.GetExecutingAssembly());

                //简单订阅方式
                //bus.Subscribe<OrderMessage>("my_test_subscriptionid", HandleTextMessage);

                //自定义消费者 ps:为什么用Assembly.GetExecutingAssembly()创建不到队列?
                autoSubscriber.SubscribeAsync(typeof(SendOrderEmailToUserConsumer).Assembly);

                Console.WriteLine("Listening for messages. Hit <return> to quit.");
                Console.ReadLine();
            }
        }
Exemplo n.º 3
0
        public When_autosubscribing_async_with_subscription_configuration_action_and_attribute()
        {
            bus = Substitute.For <IBus>();

            var autoSubscriber = new AutoSubscriber(bus, "my_app")
            {
                ConfigureSubscriptionConfiguration =
                    c => c.WithAutoDelete(false)
                    .WithExpires(11)
                    .WithPrefetchCount(11)
                    .WithPriority(11)
            };

            bus.When(x => x.SubscribeAsync(
                         Arg.Is("MyActionAndAttributeTest"),
                         Arg.Any <Func <MessageA, Task> >(),
                         Arg.Any <Action <ISubscriptionConfiguration> >()
                         ))
            .Do(a =>
            {
                capturedAction = (Action <ISubscriptionConfiguration>)a.Args()[2];
            });

            autoSubscriber.SubscribeAsync(GetType().GetTypeInfo().Assembly);
        }
Exemplo n.º 4
0
        public void Should_be_able_to_autosubscribe_with_async_to_several_messages_in_one_consumer()
        {
            var interceptedSubscriptions = new List <Tuple <string, Delegate> >();
            var busFake = new BusFake
            {
                InterceptSubscribe = (s, a) => interceptedSubscriptions.Add(new Tuple <string, Delegate>(s, a))
            };
            var autoSubscriber = new AutoSubscriber(busFake, "MyAppPrefix");

            autoSubscriber.SubscribeAsync(GetType().Assembly);

            interceptedSubscriptions.Count.ShouldEqual(3);
            interceptedSubscriptions.TrueForAll(i => i.Item2.Method.DeclaringType == typeof(DefaultAutoSubscriberMessageDispatcher)).ShouldBeTrue();

            CheckSubscriptionsContains <MessageA>(interceptedSubscriptions, "MyAppPrefix:595a495413330ce1a7d03dd6a434b599");
            CheckSubscriptionsContains <MessageB>(interceptedSubscriptions, "MyExplicitId");
            CheckSubscriptionsContains <MessageC>(interceptedSubscriptions, "MyAppPrefix:e65118ba1611619fa7afb53dc916866e");

            var messageADispatcher = (Func <MessageA, Task>)interceptedSubscriptions.Single(x => x.Item2.GetType().GetGenericArguments()[0] == typeof(MessageA)).Item2;
            var message            = new MessageA {
                Text = "Hello World"
            };

            messageADispatcher(message);
            MyAsyncConsumer.MessageAText.ShouldEqual("Hello World");
        }
Exemplo n.º 5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            var services = app.ApplicationServices.CreateScope().ServiceProvider;

            var lifeTime = services.GetService <Microsoft.Extensions.Hosting.IHostApplicationLifetime>();
            var bus      = services.GetService <IBus>();

            lifeTime.ApplicationStarted.Register(() =>
            {
                var subscriber = new AutoSubscriber(bus, "OrderService1");
                subscriber.Subscribe(Assembly.GetExecutingAssembly());
                subscriber.SubscribeAsync(Assembly.GetExecutingAssembly());
            });

            lifeTime.ApplicationStopped.Register(() => { bus.Dispose(); });
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Exemplo n.º 6
0
        public static IApplicationBuilder UseSubscriber(this IApplicationBuilder app, string prefix,
                                                        params Assembly[] assembly)
        {
            var services = app.ApplicationServices.CreateScope().ServiceProvider;

            var lifetime = services.GetService <IApplicationLifetime>();
            var bus      = services.GetService <IBus>();

            lifetime.ApplicationStarted.Register(() =>
            {
                if (bus != null)
                {
                    var subscriber = new AutoSubscriber(bus, prefix)
                    {
                        AutoSubscriberMessageDispatcher = new MessageDispatcher(app.ApplicationServices)
                    };
                    subscriber.Subscribe(assembly);
                    subscriber.SubscribeAsync(assembly);
                }
            });

            lifetime.ApplicationStopped.Register(() => bus.Dispose());

            return(app);
        }
        public When_autosubscribing_async()
        {
            //mockBuilder = new MockBuilder();
            mockBuilder = new MockBuilder();

            var autoSubscriber = new AutoSubscriber(bus: mockBuilder.Bus, subscriptionIdPrefix: "my_app");

            autoSubscriber.SubscribeAsync(typeof(MyAsyncConsumer));
        }
Exemplo n.º 8
0
        // https://github.com/EasyNetQ/EasyNetQ/wiki/Auto-Subscriber
        private static void SubscribeHandlers(IBus bus, IServiceProvider services)
        {
            var dispatcherLogger = services.GetRequiredService <ILogger <MessageDispatcher> >();
            var subscriber       = new AutoSubscriber(bus, "auto")
            {
                AutoSubscriberMessageDispatcher = new MessageDispatcher(services, dispatcherLogger),
            };

            subscriber.SubscribeAsync(Assembly.GetExecutingAssembly());
        }
Exemplo n.º 9
0
        /// <summary>
        /// 自动订阅
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="subscriptionIdPrefix"></param>
        /// <param name="topic"></param>
        /// <returns>Task</returns>
        public async Task AutoSubscribeAsync(string assemblyName, string subscriptionIdPrefix, string topic)
        {
            var subscriber = new AutoSubscriber(bus, subscriptionIdPrefix);

            if (!string.IsNullOrEmpty(topic))
            {
                subscriber.ConfigureSubscriptionConfiguration = x => x.WithTopic(topic);
            }
            await Task.Run(() => subscriber.SubscribeAsync(Assembly.Load(assemblyName)));
        }
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     if (_settings.EventHandlersAssemblies is not null)
     {
         var subscriber = new AutoSubscriber(_bus, _settings.EventHandlersAssemblies.ToString())
         {
             AutoSubscriberMessageDispatcher = new MicrosoftDiMessageDispatcher(_serviceProvider)
         };
         await subscriber.SubscribeAsync(new[] { _settings.EventHandlersAssemblies }, stoppingToken);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Subscribe to consumers from assembly
        /// </summary>
        /// <param name="cancellationToken"></param>
        public async Task Subscribe(CancellationToken cancellationToken)
        {
            var subscriber = new AutoSubscriber(_bus, "_")
            {
                ConfigureSubscriptionConfiguration = s => s.WithAutoDelete(),
                GenerateSubscriptionId             = info => "_",
                AutoSubscriberMessageDispatcher    = _messageDispatcher
            };

            await subscriber.SubscribeAsync(new[] { Assembly.GetEntryAssembly() }, cancellationToken);
        }
Exemplo n.º 12
0
        public static void UseEasyNetQ(this IApplicationBuilder app)
        {
            var bus            = app.ApplicationServices.GetRequiredService <IBus>();
            var autoSubscriber = new AutoSubscriber(bus, "productor")
            {
                AutoSubscriberMessageDispatcher = app.ApplicationServices.GetRequiredService <IAutoSubscriberMessageDispatcher>()
            };

            autoSubscriber.Subscribe(Assembly.GetExecutingAssembly());
            autoSubscriber.SubscribeAsync(Assembly.GetExecutingAssembly());
        }
Exemplo n.º 13
0
        public static void UseEasyNetQ(this IApplicationBuilder app)
        {
            var bus            = app.ApplicationServices.GetRequiredService <IBus>();
            var autoSubscriber = new AutoSubscriber(bus, "consumer")
            {
                AutoSubscriberMessageDispatcher    = app.ApplicationServices.GetRequiredService <IAutoSubscriberMessageDispatcher>(),
                GenerateSubscriptionId             = x => AppDomain.CurrentDomain.FriendlyName + x.ConcreteType.Name,
                ConfigureSubscriptionConfiguration = x => x.WithAutoDelete(true).WithDurable(true)
            };

            autoSubscriber.Subscribe(Assembly.GetExecutingAssembly());
            autoSubscriber.SubscribeAsync(Assembly.GetExecutingAssembly());
        }
Exemplo n.º 14
0
        public void LoadSubscribers(Assembly assembly, string subscriptionId, IContainer container)
        {
            _logService.Debug("Loading Subscribers from assembly: {0}, subscriptionId: {1}, container: {2}", assembly, subscriptionId, container);

            var autosubscriber = new AutoSubscriber(_bus, subscriptionId)
            {
                ConfigureSubscriptionConfiguration = configuration => configuration.WithPrefetchCount(_defaultHostConfiguration.PreFetchCount),
                AutoSubscriberMessageDispatcher    = new StructureMapMessageDispatcher(container)
            };

            autosubscriber.Subscribe(assembly);
            autosubscriber.SubscribeAsync(assembly);

            _logService.Debug("Loaded and Subscribed Subscribers from assembly: {0}, subscriptionId: {1}, container: {2}", assembly, subscriptionId, container);
        }
Exemplo n.º 15
0
        public static IApplicationBuilder UseSubscribe(this IApplicationBuilder app, string subscriptionIdPrefix, Assembly assembly)
        {
            var services = app.ApplicationServices.CreateScope().ServiceProvider;
            var lifeTime = services.GetService <IHostApplicationLifetime>();
            var bus      = services.GetService <IBus>();

            lifeTime.ApplicationStarted.Register(() =>
            {
                var subscriber = new AutoSubscriber(bus, subscriptionIdPrefix);
                subscriber.Subscribe(assembly);
                subscriber.SubscribeAsync(assembly);
            });
            lifeTime.ApplicationStopped.Register(() => { bus.Dispose(); });
            return(app);
        }
Exemplo n.º 16
0
        public static void AddSubscriber <T>(this IServiceCollection services, string name = null)
        {
            services.AddSingleton(typeof(T));
            var provider        = services.BuildServiceProvider();
            var rabbitMqManager = provider.GetService <RabbitMqManager>();

            if (rabbitMqManager != null)
            {
                var bus            = string.IsNullOrEmpty(name) ? rabbitMqManager.Default : rabbitMqManager.GetBus(name);
                var autoSubscriber = new AutoSubscriber(bus, "")
                {
                    AutoSubscriberMessageDispatcher = new ConsumerMessageDispatcher(provider)
                };
                autoSubscriber.Subscribe(new Type[] { typeof(T) });
                autoSubscriber.SubscribeAsync(new Type[] { typeof(T) });
            }
        }
        public When_autosubscribing_async_explicit_implementation_with_subscription_configuration_attribute()
        {
            bus = Substitute.For <IBus>();

            var autoSubscriber = new AutoSubscriber(bus, "my_app");

            bus.When(x => x.SubscribeAsync(
                         Arg.Is("MyAttrTest"),
                         Arg.Any <Func <MessageA, Task> >(),
                         Arg.Any <Action <ISubscriptionConfiguration> >()
                         ))
            .Do(a =>
            {
                capturedAction = (Action <ISubscriptionConfiguration>)a.Args()[2];
            });

            autoSubscriber.SubscribeAsync(GetType().GetTypeInfo().Assembly);
        }
Exemplo n.º 18
0
        public static IApplicationBuilder UseSubscriber(this IApplicationBuilder app, string prefix,
                                                        params Assembly[] assembly)
        {
            var services = app.ApplicationServices.CreateScope().ServiceProvider;

            var lifetime = services.GetService <IApplicationLifetime>();
            var bus      = services.GetService <IBus>();

            var container = new WindsorContainer();

            container.Register(
                //Маппер
                Component.For <IMapper>().Instance(services.GetService <IMapper>()),

                //Сервисы
                Component.For <INotificationService>().Instance(services.GetService <INotificationService>()),
                Component.For <IEmailNotificationService>().Instance(services.GetService <IEmailNotificationService>()),
                Component.For <ISubscriptionService>().Instance(services.GetService <ISubscriptionService>()),
                Component.For <IUserService>().Instance(services.GetService <IUserService>()),

                //Потребители
                Component.For <RegistrationNotificationMessageConsumer>().ImplementedBy <RegistrationNotificationMessageConsumer>(),
                Component.For <SubscribersNotificationMessageConsumer>().ImplementedBy <SubscribersNotificationMessageConsumer>(),
                Component.For <UserNotificationMessageConsumer>().ImplementedBy <UserNotificationMessageConsumer>(),
                Component.For <UserSubscriptionMessageConsumer>().ImplementedBy <UserSubscriptionMessageConsumer>(),
                Component.For <UserUnsubscriptionMessageConsumer>().ImplementedBy <UserUnsubscriptionMessageConsumer>(),

                //Конфиг
                Component.For <IConfiguration>().Instance(services.GetService <IConfiguration>()));

            lifetime.ApplicationStarted.Register(() =>
            {
                var subscriber = new AutoSubscriber(bus, prefix)
                {
                    AutoSubscriberMessageDispatcher = new WindsorMessageDispatcher(container)
                };
                subscriber.Subscribe(assembly);
                subscriber.SubscribeAsync(assembly);
            });

            lifetime.ApplicationStopped.Register(() => bus.Dispose());

            return(app);
        }
Exemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="appBuilder"></param>
        /// <param name="service">Topic, that define routing key.</param>
        /// <param name="assemblyType">Represent identifier of Assebmly that contains complete implementation of consumer.</param>
        /// <returns></returns>
        public static IApplicationBuilder UseSubscribe(this IApplicationBuilder appBuilder, Shopping.Common.Enums.Service service, Type assemblyType)
        {
            var bus      = appBuilder.ApplicationServices.GetService(typeof(IBus)) as IBus;
            var lifeTime = appBuilder.ApplicationServices.GetService(typeof(IApplicationLifetime)) as IApplicationLifetime;

            var assembly = assemblyType.Assembly;

            lifeTime.ApplicationStarted.Register(() =>
            {
                var subscriber = new AutoSubscriber(bus, assemblyType.Name)
                {
                    ConfigureSubscriptionConfiguration = config => config.WithTopic(service.ToString())
                };
                subscriber.Subscribe(assembly);
                subscriber.SubscribeAsync(assembly);
            });

            lifeTime.ApplicationStopped.Register(() => bus.Dispose());

            return(appBuilder);
        }
Exemplo n.º 20
0
        public static IApplicationBuilder UseAutoSubscribe(this IApplicationBuilder appBuilder, string subscriptionIdPrefix, Assembly assembly)
        {
            var services = appBuilder.ApplicationServices.CreateScope().ServiceProvider;

            var lifeTime = services.GetService <IApplicationLifetime>();
            var bus      = services.GetService <IBus>();

            lifeTime.ApplicationStarted.Register(() =>
            {
                var subscriber = new AutoSubscriber(bus, subscriptionIdPrefix)
                {
                    AutoSubscriberMessageDispatcher = new DependencyInjectionMessageDispatcher(services)
                };

                subscriber.Subscribe(assembly);
                subscriber.SubscribeAsync(assembly);
            });

            lifeTime.ApplicationStopped.Register(() => bus.Dispose());

            return(appBuilder);
        }
Exemplo n.º 21
0
        public static IApplicationBuilder UseSubscriber(this IApplicationBuilder app, string prefix, Assembly assembly)
        {
            var services = app.ApplicationServices.CreateScope().ServiceProvider;

            var lifetime = services.GetService <IApplicationLifetime>();
            var bus      = services.GetService <IBus>();

            //register our consumer with our IoC container
            var container = new WindsorContainer();

            container.Register(
                //регистраци потребителей
                Component.For <UserMessageConsumer>().ImplementedBy <UserMessageConsumer>(),

                //сервисы
                Component.For <IChatService>().Instance(services.GetService <IChatService>()),

                //мапперы
                Component.For <IMapper>().Instance(services.GetService <IMapper>())
                );

            lifetime.ApplicationStarted.Register(() =>
            {
                var subscriber = new AutoSubscriber(bus, prefix)
                {
                    AutoSubscriberMessageDispatcher = new WindsorMessageDispatcher(container)
                };
                subscriber.Subscribe(assembly);
                subscriber.SubscribeAsync(assembly);
            });

            lifetime.ApplicationStopped.Register(() =>
            {
                container.Dispose();
                bus.Dispose();
            });

            return(app);
        }
Exemplo n.º 22
0
        protected override async Task StartAsyncCritical(CancellationToken cancellationToken)
        {
            await _bus.Rpc.RespondAsync <SimpleMessageParam, SimpleMessageResponse>(_responseService.CreateSimpleMessageResponse, cancellationToken);

            await _subscriber.SubscribeAsync(Assembly.GetExecutingAssembly().GetTypes(), cancellationToken);
        }
Exemplo n.º 23
0
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     await _autoSubscriber.SubscribeAsync(new Assembly[] { Assembly.GetExecutingAssembly() }, stoppingToken);
 }