public IBus CreateConsumerBus(string connectionStringKey, ConsumerRegistration consumers)
        {
            var appSettings = new AppSettings();
            var connectionString = appSettings.ConnectionStrings.Get(connectionStringKey, () => DefaultConnection);
            var subscriptionPrefix = appSettings.RabbitMQ.SubscriptionPrefix;

            try
            {
                var bus = CreateBus(connectionStringKey, null);

                var dispatcher = new NoMagicAutoDispatcher(consumers);
                var autoSubscriber = new AutoSubscriber(bus, subscriptionPrefix)
                                     {
                                         AutoSubscriberMessageDispatcher = dispatcher
                                     };

                var consumerAssemblies = consumers.GetAssemblies();
                autoSubscriber.Subscribe(consumerAssemblies);
                

                Log.DebugFormat("Connected to RabbitMQ on {0} and using subscription prefix {1}", connectionString, subscriptionPrefix);

                return bus;
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Failed to create a bus for RabbitMQ with connectionstring: {0}", connectionString);
                Log.ErrorFormat("The failure was {0}", e.Message);

                throw;
            }
        }
        public When_autosubscribing()
        {
            mockBuilder = new MockBuilder();
//            mockBuilder = new MockBuilder(x => x.Register<IEasyNetQLogger, ConsoleLogger>());

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

            parameters = new Dictionary <string, object>();
            autoSubscriber.Subscribe(typeof(MyAsyncConsumer), typeof(MyConsumer), typeof(MyGenericAbstractConsumer <>));
        }
        public When_autosubscribing_with_explicit_implementation()
        {
            //mockBuilder = new MockBuilder();
            mockBuilder = new MockBuilder();

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

            parameters = new Dictionary <string, object>();
            autoSubscriber.Subscribe(typeof(MyConsumer), typeof(MyGenericAbstractConsumer <>));
        }
示例#4
0
        /// <summary>
        /// 自动订阅
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="subscriptionIdPrefix"></param>
        /// <param name="topic"></param>
        public void AutoSubscribe(string assemblyName, string subscriptionIdPrefix, string topic)
        {
            var subscriber = new AutoSubscriber(bus, subscriptionIdPrefix);

            if (!string.IsNullOrEmpty(topic))
            {
                subscriber.ConfigureSubscriptionConfiguration = x => x.WithTopic(topic);
            }
            subscriber.Subscribe(Assembly.Load(assemblyName));
        }
示例#5
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());
        }
        public void Start()
        {
            //todo move strings to configs
            _container.Register(Classes.FromThisAssembly().BasedOn(typeof(IConsume<>)).WithServiceSelf());

            var autoSubscriber = new AutoSubscriber(_bus, "My_subscription_id_prefix")
            {
                AutoSubscriberMessageDispatcher = new WindsorMessageDispatcher(_container, _logger)
            };

            autoSubscriber.Subscribe(Assembly.GetExecutingAssembly());
        }
示例#7
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());
        }
示例#8
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);
        }
示例#9
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);
        }
        public When_autosubscribing_with_subscription_configuration_attribute_no_expires()
        {
            bus = Substitute.For <IBus>();

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

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

            autoSubscriber.Subscribe(GetType().GetTypeInfo().Assembly);
        }
示例#11
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) });
            }
        }
示例#12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSignalR(routes =>
            {
                routes.MapHub <StatHub>("/stats");
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            var bus        = app.ApplicationServices.GetService <IBus>();
            var subscriber = new AutoSubscriber(bus, "ProductMessageService")
            {
                AutoSubscriberMessageDispatcher = app.ApplicationServices.GetService <MessageDispatcher>(),
            };

            // -- should use EasyNetQ version from 3.6.0 (3.0-3.5 doesn't work properly)
            try
            {
                Thread.Sleep(10000); // waiting for RabbitMQ server is loaded
                subscriber.Subscribe(new Assembly[] { GetType().Assembly });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
        }
        public When_autosubscribing_with_subscription_configuration_attribute_no_expires()
        {
            pubSub = Substitute.For <IPubSub>();
            bus    = Substitute.For <IBus>();
            bus.PubSub.Returns(pubSub);

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

            pubSub.SubscribeAsync(
                Arg.Is("MyAttrTest"),
                Arg.Any <Func <MessageA, CancellationToken, Task> >(),
                Arg.Any <Action <ISubscriptionConfiguration> >()
                )
            .Returns(Task.FromResult(Substitute.For <ISubscriptionResult>()).ToAwaitableDisposable())
            .AndDoes(a => capturedAction = (Action <ISubscriptionConfiguration>)a.Args()[2]);

            autoSubscriber.Subscribe(new[] { typeof(MyConsumerWithAttr) });
        }
        public void SetUp()
        {
            bus = MockRepository.GenerateMock <IBus>();

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

            bus.Stub(x => x.Subscribe(
                         Arg <string> .Is.Equal("MyAttrTest"),
                         Arg <Action <MessageA> > .Is.Anything,
                         Arg <Action <ISubscriptionConfiguration> > .Is.Anything
                         ))
            .WhenCalled(a =>
            {
                capturedAction = (Action <ISubscriptionConfiguration>)a.Arguments[2];
            });

            autoSubscriber.Subscribe(GetType().Assembly);
        }
示例#15
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);
        }
示例#16
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            //.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true);

            Configuration = builder.Build();
            var services = new ServiceCollection();

            services.AddSingleton <IConfigurationRoot>(Configuration);
            services.AddSingleton(new LoggerFactory()
                                  .AddConsole()
                                  .AddDebug());
            services.AddLogging();

            // app settings
            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            var provider   = services.BuildServiceProvider();
            var connection = new ConnectionConfiguration();

            connection.Port     = 5672;
            connection.UserName = "******";
            connection.Password = "******";

            connection.Hosts = new List <HostConfiguration> {
                new HostConfiguration()
                {
                    Host = @"rabbitmq", Port = 5672
                }
            };
            connection.ConnectIntervalAttempt = TimeSpan.FromSeconds(4);
            connection.RequestedHeartbeat     = 6;
            connection.Timeout = 60;
            var _bus = RabbitHutch.CreateBus(connection, ser => ser.Register <IEasyNetQLogger>(logger => new DoNothingLogger()));


            var subscriber = new AutoSubscriber(_bus, "#");

            subscriber.Subscribe(Assembly.GetExecutingAssembly());
            Console.WriteLine("Notifications EventHandler Listening");
            string typed = Console.ReadLine();
        }
示例#17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMapper autoMapper)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                autoMapper.ConfigurationProvider.AssertConfigurationIsValid();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            //app.UseCors("CorsPolicy");
            app.UseHttpsRedirection();
            app.UseMvc();
            app.UseSwagger().UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Products.Database");
                //c.ConfigureOAuth2("swagger", "secret".Sha256(), "swagger");
            });
            var bus        = app.ApplicationServices.GetService <IBus>();
            var subscriber = new AutoSubscriber(bus, "ProductMessageService")
            {
                AutoSubscriberMessageDispatcher = app.ApplicationServices.GetService <MessageDispatcher>(),
            };

            // -- should use EasyNetQ version from 3.6.0 (3.0-3.5 doesn't work properly)
            try
            {
                Thread.Sleep(10000); // waiting for RabbitMQ server is loaded
                subscriber.Subscribe(new Assembly[] { GetType().Assembly });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

            //var consumer = app.ApplicationServices.GetService<MessagesConsumer>();
            //bus.SubscribeAsync<ProductDTO>("ProductMessageService", async message =>
            //{
            //    await consumer.ConsumeAsync(message);
            //});
        }
示例#18
0
文件: Program.cs 项目: z0c/drifter
        // ReSharper disable once UnusedParameter.Local
        private static void Main(string[] args)
        {
            LoggerConfig.ConfigureLogger();
            var container = UnityConfig.RegisterComponents();

            RabbitHutch.SetContainerFactory(() => new UnityAdapter(container));

            using (var bus = RabbitHutch.CreateBus(ConfigurationManager.ConnectionStrings["RabbitMQ"].ConnectionString))
            {
                var autoSubscriber = new AutoSubscriber(bus, "Worker")
                {
                    AutoSubscriberMessageDispatcher = new UnityMessageDispatcher(container)
                };

                autoSubscriber.Subscribe(Assembly.GetExecutingAssembly());
                autoSubscriber.SubscribeAsync(Assembly.GetExecutingAssembly());

                Console.ReadLine();
            }
        }
示例#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);
        }
示例#20
0
        public void Should_be_able_to_take_control_of_subscription_id_generation()
        {
            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")
            {
                GenerateSubscriptionId = c => c.MessageType.Name.ToString(CultureInfo.InvariantCulture)
            };

            autoSubscriber.Subscribe(GetType().Assembly);

            interceptedSubscriptions.Count.ShouldEqual(4);

            CheckSubscriptionsContains <MessageA>(interceptedSubscriptions, "MessageA");
            CheckSubscriptionsContains <MessageB>(interceptedSubscriptions, "MyExplicitId");
            CheckSubscriptionsContains <MessageC>(interceptedSubscriptions, "MessageC");
        }
示例#21
0
        static void Main(string[] args)
        {
            // Create a bus instance.
            IBus bus = AzureCloud
                       .ConfigureBus()
                       .WithPublishConfiguration((c) => c.WithMessageMetadata((m, configure) =>
            {
                configure.Add("Message.Activo", ((SampleMessage)m).Activo);
            }))
                       ////.WithSubscriptionConfiguration((c) => c.WithTopicByMessageNamespace())
                       .CreateBus();

            // Subscribe to messages.
            var autoSubscriber = new AutoSubscriber(bus, "AzureBus.Sample.Console");

            autoSubscriber.Subscribe(Assembly.GetExecutingAssembly());

            var activo = true;

            // Send 100 messages.
            for (int i = 0; i < 10; i++)
            {
                activo = !activo;
                bus.Publish(new SampleMessage(i.ToString(), activo));
            }

            ////// Create a Queue instance
            ////IQueue queue = AzureCloud.CreateQueue();

            ////// Send 100 messages.
            ////for (int i = 0; i < 10; i++)
            ////{
            ////    queue.Send(new SampleMessage(i.ToString()));
            ////}

            ////// Subscribe to queue for messages of type SampleMessage
            ////queue.Subscribe<SampleMessage>((m) => Console.WriteLine(string.Format("Message received from Queue: Value = {0}", m.Value)));

            Console.ReadKey();
        }
示例#22
0
        static void Main(string[] args)
        {
            using (var bus = RabbitHutch.CreateBus("host=localhost", x => x.Register <IEasyNetQLogger>(_ => new ConsoleLogger())))
            {
                //bus.Subscribe<TextMessage>("test", HandleTextMessage);

                //bus.Receive<TextMessage>("build.queue", x => HandleTextMessage(x));

                //var subscriber = new AutoSubscriber(bus, "my_applications_subscriptionId_prefix");

                var subscriber = new AutoSubscriber(bus, "My_subscription_id_prefix")
                {
                    AutoSubscriberMessageDispatcher = new WindsorMessageDispatcher()
                };
                //autoSubscriber.Subscribe(GetType().Assembly);

                subscriber.Subscribe(Assembly.GetExecutingAssembly());

                Console.WriteLine("Listening for messages. Hit <return> to quit.");
                Console.ReadLine();
            }
        }
示例#23
0
        public bool Start()
        {
            Log.Info("ApiPushService starting");

            var bus = RabbitHutch.CreateBus(_configuration.RabbitMqConnectionString, register => register.Register<IEasyNetQLogger>(_ => new EasyNetQLogger()));

            var subscriber = new AutoSubscriber(bus, "name")
            {
                ConfigureSubscriptionConfiguration = c =>
                {
                    c.WithPrefetchCount(_configuration.PrefetchCount);
                    c.WithAutoDelete(_configuration.AutoDelete);
                },
                GenerateSubscriptionId = info => info.ConcreteType.FullName,
                AutoSubscriberMessageDispatcher = _dispatcher
            };

            subscriber.Subscribe(Assembly.GetExecutingAssembly());

            Log.Info("ApiPushService started");
            return true;
        }
        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(() =>
            {
                var subscriber = new AutoSubscriber(bus, prefix)
                {
                    AutoSubscriberMessageDispatcher = new MessageDispatcher(app.ApplicationServices)
                };
                subscriber.Subscribe(assembly);
                subscriber.SubscribeAsync(assembly);
            });

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

            return(app);
        }
示例#25
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);
        }
示例#26
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);
        }
示例#27
0
        public void Should_be_able_to_autosubscribe_to_several_messages_in_one_consumer_with_custom_interface()
        {
            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.Subscribe(typeof(IConsumeCustom <>), GetType().Assembly);

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

            interceptedSubscriptions[0].Item1.ShouldEqual("MyAppPrefix:63c317b761366d57679a8bb0f7fa925a");
            interceptedSubscriptions[0].Item2.Method.GetParameters()[0].ParameterType.ShouldEqual(typeof(MessageA));

            interceptedSubscriptions[1].Item1.ShouldEqual("MyExplicitId");
            interceptedSubscriptions[1].Item2.Method.GetParameters()[0].ParameterType.ShouldEqual(typeof(MessageB));

            interceptedSubscriptions[2].Item1.ShouldEqual("MyAppPrefix:813fd8f08e61068e054dcff403da5ce7");
            interceptedSubscriptions[2].Item2.Method.GetParameters()[0].ParameterType.ShouldEqual(typeof(MessageC));
        }
示例#28
0
        public void Should_be_able_to_autosubscribe_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.Subscribe(GetType().Assembly);

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

            interceptedSubscriptions[0].Item1.ShouldEqual("MyAppPrefix:e8afeaac27aeba31a42dea8e4d05308e");
            interceptedSubscriptions[0].Item2.Method.GetParameters()[0].ParameterType.ShouldEqual(typeof(MessageA));

            interceptedSubscriptions[1].Item1.ShouldEqual("MyExplicitId");
            interceptedSubscriptions[1].Item2.Method.GetParameters()[0].ParameterType.ShouldEqual(typeof(MessageB));

            interceptedSubscriptions[2].Item1.ShouldEqual("MyAppPrefix:cf5f54ed13478763e2da2bb3c9487baa");
            interceptedSubscriptions[2].Item2.Method.GetParameters()[0].ParameterType.ShouldEqual(typeof(MessageC));
        }
示例#29
0
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();

            kernel.RegisterAsEasyNetQContainerFactory();

            var bus = RabbitHutch.CreateBus("host=vmdcvppt1", reg => reg.RegisterXXXServices().Register <IEasyNetQLogger, ConsoleLogger>());

            kernel.Bind <IMessagePublisher>().ToConstant(new RabbitMessagePublisher(bus));
            kernel.Bind <Stock>().To <Stock>().InSingletonScope(); //the "Stock" consumer stores state in a field variable, make sure it's not lost between requests

            var autoSubscriber = new AutoSubscriber(bus, "SystemTest")
            {
                ConfigureSubscriptionConfiguration = x => x.WithAutoDelete(),
                AutoSubscriberMessageDispatcher    = new NinjectMessageDispatcher(kernel)
            };

            autoSubscriber.Subscribe(typeof(Stock).Assembly);

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

            bus.Dispose();
        }
示例#30
0
        public void Should_be_able_to_use_a_custom_message_dispatcher()
        {
            var interceptedSubscriptions = new List <Tuple <string, Delegate> >();
            var busFake = new BusFake
            {
                InterceptSubscribe = (s, a) => interceptedSubscriptions.Add(new Tuple <string, Delegate>(s, a))
            };

            var dispatcher = new CustomMessageDispatcher();

            var autoSubscriber = new AutoSubscriber(busFake, "MyAppPrefix")
            {
                MessageDispatcher = dispatcher
            };

            autoSubscriber.Subscribe(GetType().Assembly);

            var messageADispatcher = (Action <MessageA>)interceptedSubscriptions.Single(x => x.Item2.GetType().GetGenericArguments()[0] == typeof(MessageA)).Item2;
            var message            = new MessageA();

            messageADispatcher(message);

            dispatcher.DispatchedMessage.ShouldBeTheSameAs(message);
        }
示例#31
0
        public RabbitMQService(IBus bus,
                               HubLifetimeManager <AudioProcessingHub> audioProcessingHub,
                               HubLifetimeManager <UserUpdatesHub> userUpdateHub,
                               IServiceScopeFactory serviceScopeFactory, ILogger <RabbitMQService> logger)
        {
            _bus = bus;
            _audioProcessingHub = audioProcessingHub;
            _userUpdateHub      = userUpdateHub;
            _logger             = logger;

            _subscriber = new AutoSubscriber(_bus, "_applications_subscriptionId_prefix");
            _subscriber.Subscribe(new[] { Assembly.GetExecutingAssembly() });
            try {
                _bus.PubSub.Subscribe <RealtimeUpdateMessage>(
                    "podnoms_message_realtimeupdate",
                    message => {
                    _logger.LogInformation(
                        $"(RabbitMQService) Consuming: {message.Message}\n\tUser: {message.UserId}");
                    _userUpdateHub.SendUserAsync(
                        message.UserId,
                        message.ChannelName,
                        new object[] { message });
                });
                _bus.PubSub.Subscribe <ProcessingUpdateMessage>(
                    "podnoms_message_audioprocessing",
                    message => {
                    _logger.LogInformation(
                        $"(RabbitMQService) Consuming: {message.Data}\n\tUser: {message.UserId}");
                    _audioProcessingHub.SendUserAsync(
                        message.UserId,
                        message.ChannelName,
                        new[] { message.Data });
                });
                _bus.PubSub.Subscribe <NotifyUserMessage>(
                    "podnoms_message_notifyuser",
                    message => {
                    _logger.LogDebug($"(RabbitMQService) Consuming: {message.Body}");
                    using var scope = serviceScopeFactory.CreateScope();
                    var service     =
                        scope.ServiceProvider.GetRequiredService <INotifyJobCompleteService>();
                    service.NotifyUser(
                        message.UserId,
                        message.Title,
                        message.Body,
                        message.Target,
                        message.Image, NotificationOptions.UploadCompleted);
                }
                    );
                _bus.PubSub.Subscribe <CustomNotificationMessage>(
                    "podnoms_message_customnotification",
                    message => {
                    _logger.LogDebug($"(RabbitMQService) Consuming: {message.Body}");
                    using var scope = serviceScopeFactory.CreateScope();
                    var service     =
                        scope.ServiceProvider.GetRequiredService <INotifyJobCompleteService>();
                    service.SendCustomNotifications(
                        message.PodcastId,
                        "YOU NEED TO CHANGE THIS",
                        "PodNoms",
                        $"{message.Title} has finished processing",
                        message.Url);
                }
                    );
            } catch (Exception e) {
                _logger.LogError("Unable to start realtime queue listeners");
                _logger.LogError(e.Message);
            }
        }
        public IBus CreateBus(string connectionStringKey, IWindsorContainer container)
        {
            var appSettings = new AppSettings();
            var connectionString = appSettings.ConnectionStrings.Get(connectionStringKey, () => DefaultConnection);
            var subscriptionPrefix = appSettings.RabbitMQ.SubscriptionPrefix;

            try
            {

                Log.InfoFormat("Connecting to RabbitMQ via {0} and using subscription prefix {1}", connectionString, subscriptionPrefix);

                var logger = new RabbitMQLogger();

                var bus = RabbitHutch.CreateBus(connectionString, x => x.Register<IEasyNetQLogger>(p => logger));
                var autoSubscriber = new AutoSubscriber(bus, subscriptionPrefix)
                {
                    AutoSubscriberMessageDispatcher = new WindsorMessageDispatcher(container)
                };

                var registration = new ConsumerRegistration();
                var assemblies = registration.GetAssemblies(container);

                autoSubscriber.Subscribe(assemblies.ToArray());
                autoSubscriber.SubscribeAsync(assemblies.ToArray());

                Log.DebugFormat("Connected to RabbitMQ on {0} and using subscription prefix {1}", connectionString, subscriptionPrefix);

                return bus;
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Failed to create a bus for RabbitMQ with connectionstring: {0}", connectionString);
                Log.ErrorFormat("The failure was {0}", e.Message);

                throw;
            }
        }
示例#33
0
        private void Subscribe()
        {
            var subscriber = new AutoSubscriber(_bus, "DeploymentMonitor");

            subscriber.Subscribe(Assembly.GetExecutingAssembly());
        }