public OrderRollbackIntegrationCommandConsumer_Definition()
        {
            string queueName = "OrderModule.OrderRollbackIntegrationCommandConsumerQueue";

            EndpointName = queueName;
            EndpointConvention.Map <OrderRollbackIntegrationCommand>(new Uri($"queue:{queueName}"));
        }
Пример #2
0
        public static void RegisterServiceBus(this IServiceCollection services, IConfiguration config)
        {
            services.AddMassTransit(cfg =>
            {
                cfg.AddBus(ctx => Bus.Factory.CreateUsingRabbitMq(bus =>
                {
                    var configuration = config.GetSection("ServiceBus");
                    var consumer      = ctx.GetService <ISubscribe>();

                    bus.Host(configuration["Url"], c =>
                    {
                        c.Username(configuration["Username"]);
                        c.Password(configuration["Password"]);
                    });


                    bus.ReceiveEndpoint("effectory", e =>
                    {
                        e.Handler <BusMessage>(ctx => consumer.HandleMessage(ctx.Message));

                        EndpointConvention.Map <BusMessage>(e.InputAddress);
                    });
                }));
            });
        }
Пример #3
0
        static void Main(string[] args)
        {
            DataBus bus = null;

            DependencyResolver.SetDependencyResolver(new NinjectBusDependencyResolver());
            try
            {
                EndpointConvention.Map <TestMessage>(new Uri("rabbitmq://localhost/testmessage_queue"));
                MessageCorrelation.UseCorrelationId <TestMessage>(x => x.CorrelationId);
                bus = new DataBus("domer");
                bus.Start();

                for (int i = 0; i < MessageCount; i++)
                {
                    bus.Publish <TestMessage>(new TestMessage()
                    {
                        Message = $"Hello World{i}"
                    }).Wait();
                }

                //Thread.Sleep(TimeSpan.FromSeconds(20));
                Console.WriteLine($"Количество обработанных сообщений: {TestMessageHandler.Counter}");
                Console.WriteLine($"Время затрачено: {TestMessageHandler.WorkTime}");
                Console.ReadLine();
            }
            finally
            {
                bus?.Stop();
            }
        }
Пример #4
0
        public void ConfigureMassTransit(IServiceCollection services)
        {
            var busConfig = new BusConfig();

            Configuration.GetSection("BusConfig").Bind(busConfig);

            services.AddMassTransit(x =>
            {
                x.AddConsumer <MainConsumerSrv1>();

                x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    var host = cfg.Host(new Uri(busConfig.Host), h =>
                    {
                        h.Username(busConfig.Username);
                        h.Password(busConfig.Password);
                    });

                    cfg.ReceiveEndpoint(host, "request-service-1-queue", ep =>
                    {
                        ep.ConfigureConsumer <MainConsumerSrv1>(provider);
                    });
                }));
            });

            EndpointConvention.Map <IGatewayRequest>(new Uri("rabbitmq://localhost/request-service-main-queue"));
            EndpointConvention.Map <IService2Request>(new Uri("rabbitmq://localhost/request-service-2-queue"));

            services.AddSingleton <IHostedService, MassTransitHostedService>();
        }
Пример #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureLogicServices();
            services.AddControllers();

            services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host("localhost", "/", h => { });

                cfg.UseExtensionsLogging(provider.GetService <ILoggerFactory>());

                cfg.ReceiveEndpoint(Constants.QueueNames.ParkingBookingQueue, e =>
                {
                    e.PrefetchCount = 16;
                    e.UseMessageRetry(x => x.Interval(2, 100));

                    e.Consumer <ParkingBookingConsumer>(provider);

                    EndpointConvention.Map <IBookingRequested>(e.InputAddress);
                });
            }));
            services.AddSingleton <IPublishEndpoint>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <ISendEndpointProvider>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>());

            //should be by namespace
            services.AddScoped(provider => provider.GetRequiredService <IBus>().CreateRequestClient <IBookingRequested>());

            services.AddSingleton <IHostedService, BusService>();
        }
        private static async Task RunAsync()
        {
            var busControl = Bus.Factory.CreateUsingRabbitMq(sbc =>
            {
                sbc.Host("rabbitmq://rabbitmq", cfg =>
                {
                    cfg.Username("guest");
                    cfg.Password("guest");
                });

                EndpointConvention.Map <Acknowledgement>(new Uri("rabbitmq://rabbitmq/message-acks"));

                sbc.ReceiveEndpoint("messages", cfg =>
                {
                    cfg.Handler <Message>(async(context) =>
                    {
                        await Console.Out.WriteLineAsync($"Received {context.Message.Text}");

                        await context.Send(new Acknowledgement
                        {
                            Id = context.Message.Text
                        });
                    });
                });
            });

            await busControl.StartAsync();

            Console.ReadLine();

            await busControl.StopAsync();
        }
Пример #7
0
        public static IServiceCollection AddMassTransit(this IServiceCollection services)
        {
            services.AddMassTransit(x =>
            {
                x.AddConsumer <BuildDetailsConsumer>();
            });

            services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                cfg.Host("localhost");

                cfg.SetLoggerFactory(provider.GetService <ILoggerFactory>());

                cfg.ReceiveEndpoint("Discord", e =>
                {
                    e.Consumer <BuildDetailsConsumer>(provider);

                    EndpointConvention.Map <BuildDetails>(e.InputAddress);
                });
            }));

            services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>());

            services.AddSingleton <IHostedService, BusService>();
            //services.AddScoped(provider => provider.GetRequiredService<IBus>());

            return(services);
        }
Пример #8
0
        public async Task BuildingFlowGraph_ShouldBuild()
        {
            EndpointConvention.Map <EFoo>(new Uri("queue:input-queue"));

            var harness = new InMemoryTestHarness()
            {
                TestTimeout = TimeSpan.FromSeconds(1)
            };

            harness.Consumer(() => new AFooConsumer());
            harness.Consumer(() => new BFooConsumer());
            harness.Consumer(() => new CFooConsumer());
            harness.Consumer(() => new DFooConsumer());
            harness.Consumer(() => new EFooConsumer());

            await harness.Start();

            await harness.Bus.Publish <AFoo>(new {
                CorrelationId = Guid.NewGuid()
            });

            await harness.Bus.Publish <BFoo>(new {
                CorrelationId = Guid.NewGuid()
            });

            var graph = await GraphGenerator.Generate(harness);

            var converstationGraphs = string.Join(Environment.NewLine,
                                                  graph.Select(StringGraphRenderer.Render));

            await harness.Stop();

            this.Assent(converstationGraphs);
        }
Пример #9
0
        public static IServiceCollection RegisterMqServices(this IServiceCollection services, IConfiguration Configuration)
        {
            services.AddScoped <SendMessageConsumer>();
            services.AddMassTransit(c =>
            {
                c.AddConsumer <SendMessageConsumer>();
            });

            services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(
                                      cfg =>
            {
                var host = cfg.Host("localhost", "/", h => { });

                cfg.ReceiveEndpoint(host, "web-service-endpoint", e =>
                {
                    e.PrefetchCount = 16;
                    //e.UseMessageRetry(x => x.(2, 100));
                    //e.UseMessageRetry(r =>
                    //{
                    //    r.Handle<ArgumentNullException>();
                    //    r.Ignore(typeof(InvalidOperationException), typeof(InvalidCastException));
                    //    r.Ignore<ArgumentException>(t => t.ParamName == "orderTotal");
                    //});

                    e.LoadFrom(provider);
                    EndpointConvention.Map <SendMessageConsumer>(e.InputAddress);
                });
            }));

            services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <IHostedService, BusService>();

            return(services);
        }
Пример #10
0
        public static void AddMessageBus(this IServiceCollection services, MessageBusConfig config)
        {
            var consumers = config.AssemblyNamesToScan.Select(Assembly.Load)
                            .Where(a => !a.IsDynamic)
                            .SelectMany(a => a.GetTypes())
                            .Where(t => t.GetInterfaces().Contains(typeof(IConsumer)) &&
                                   !t.Namespace.StartsWith("MassTransit") &&
                                   t.IsClass && !t.IsAbstract)
                            .ToList();

            foreach (var consumer in consumers)
            {
                services.AddScoped(consumer);
            }

            services.AddMassTransit(x =>
            {
                var method = x.GetType().GetMethod("AddConsumer");

                foreach (var consumer in consumers)
                {
                    var generic = method.MakeGenericMethod(consumer);
                    generic.Invoke(x, null);
                }
            });

            services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host(config.HostName, "/", h =>
                {
                    h.Username(config.UserName);
                    h.Password(config.Password);
                });

                cfg.UseNLog();

                cfg.OverrideDefaultBusEndpointQueueName($"{config.ApiName}-{Environment.MachineName}-{Guid.NewGuid().ToString("N")}");

                cfg.ReceiveEndpoint(host, config.ApiName, e =>
                {
                    e.Durable    = true;
                    e.AutoDelete = false;

                    // Set up EndpointConventions

                    EndpointConvention.Map <IAbsenceApproved>(e.InputAddress);

                    e.LoadFrom(provider);
                });
            }));

            services.AddSingleton <IPublishEndpoint>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <ISendEndpointProvider>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>());

            // Create request clients
            //services.AddScoped(provider => provider.GetRequiredService<IBus>().CreateRequestClient<SubmitOrder>());

            services.AddSingleton <IHostedService, BusService>();
        }
Пример #11
0
        public async Task Should_generate_a_graph_of_the_message_flow()
        {
            var harness = new InMemoryTestHarness
            {
                TestTimeout           = TimeSpan.FromSeconds(2),
                TestInactivityTimeout = TimeSpan.FromSeconds(2)
            };

            harness.Consumer(() => new AFooConsumer());
            harness.Consumer(() => new BFooConsumer());
            harness.Consumer(() => new CFooConsumer());
            harness.Consumer(() => new DFooConsumer());
            harness.Consumer(() => new EFooConsumer());

            EndpointConvention.Map <EFoo>(harness.InputQueueAddress);

            await harness.Start();

            await harness.Bus.Publish <AFoo>(new { InVar.CorrelationId });

            await harness.Bus.Publish <BFoo>(new { InVar.CorrelationId });

            await harness.OutputTimeline(TestContext.Out, options => options.IncludeAddress());

            await harness.Stop();
        }
Пример #12
0
        /// <summary>
        /// Configures a <see cref="ISendEndpoint"/> mock to expect a expected. Returned mock can be verified.
        /// </summary>
        /// <param name="mockEndpointProvider"></param>
        /// <param name="expected"></param>
        /// <typeparam name="TMessage"></typeparam>
        /// <returns></returns>
        public static Mock <ISendEndpoint> SetupMessage <TMessage>(this Mock <ISendEndpointProvider> mockEndpointProvider, object expected)
            where TMessage : class
        {
            if (!EndpointConvention.TryGetDestinationAddress <TMessage>(out var destinationAddress))
            {
                // this is just a mock, so the real value shouldn't matter here as long as we're not mixing
                // integration tests and mock tests in the same suite. Use the same convention as the
                // MassTransitInMemoryTestHarness just in case...
                EndpointConvention.Map <TMessage>(new Uri("http://localhost/input-queue"));
            }

            var mockEndpoint = new Mock <ISendEndpoint>();

            mockEndpointProvider
            .Setup(x => x.GetSendEndpoint(It.IsAny <Uri>()))
            .Returns(Task.FromResult(mockEndpoint.Object))
            .Verifiable();

            mockEndpoint
            .Setup(x => x.Send <TMessage>(AnonymousType.Matches <TMessage>(expected), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            return(mockEndpoint);
        }
Пример #13
0
 public static IServiceCollection AddMobileCodeSender(this IServiceCollection services, IBusControl bus, string host)
 {
     services.AddSingleton <IMobileCodeSender>(u => new MobileCodeSender(bus));
     EndpointConvention.Map <SendMobileCodeCommand>(
         new Uri(host + "OM.Base.Csi.SmsService"));
     return(services);
 }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService <ParkingBookingWorker>();
            services.AddHostedService <StatisticWorker>();

            services.ConfigureLogicServices();

            services.AddScoped <IParkingBookingConsumer, ParkingBookingConsumer>();

            services.AddScoped <ParkingBookingConsumer>();
            services.AddMassTransit(x =>
            {
                // add the consumer to the container
                x.AddConsumer <ParkingBookingConsumer>();
            });

            services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host("localhost", "/", h => { });

                cfg.UseExtensionsLogging(provider.GetService <ILoggerFactory>());

                cfg.ReceiveEndpoint(Constants.QueueNames.ParkingBookingQueue, e =>
                {
                    e.PrefetchCount = 16;
                    e.UseMessageRetry(x => x.Interval(2, 100));
                    e.Consumer <ParkingBookingConsumer>(provider);


                    EndpointConvention.Map <IBookingRequested>(e.InputAddress);
                });
            }));
        });
Пример #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddDbContext <ZombieDiceDbContext>(options =>
            {
                options.UseInMemoryDatabase("ZombieDice");
            });

            services.AddMassTransit(c =>
            {
                c.AddConsumer <NewGameConsumer>();

                c.UsingRabbitMq((context, cfg) =>
                {
                    cfg.Host("rabbitmq://rabbitmq");

                    cfg.ReceiveEndpoint("game-created", e =>
                    {
                        e.ConfigureConsumer <NewGameConsumer>(context);
                    });
                });
            });

            EndpointConvention.Map <GameDto[]>(new Uri("queue:game-state-updated"));
            services.AddMassTransitHostedService();
        }
Пример #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddScoped <IService, Service>();
            //services.AddScoped<DoSomethingConsumer>();
            //services.AddMassTransit(x =>
            //{
            //    // add the consumer to the container
            //    x.AddConsumer<DoSomethingConsumer>();
            //});

            services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host("localhost", "/", h => { });

                //cfg.UseExtensionsLogging(provider.GetService<Microsoft.Extensions.Logging.ILoggerFactory>());

                cfg.ReceiveEndpoint(host, "web-service-endpoint", e =>
                {
                    e.PrefetchCount = 16;
                    e.UseMessageRetry(x => x.Interval(2, 100));
                    //e.Consumer<DoSomethingConsumer>(provider);
                    EndpointConvention.Map <Message>(e.InputAddress);
                });
            }));

            services.AddSingleton <IPublishEndpoint>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <ISendEndpointProvider>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>());

            services.AddScoped(provider => provider.GetRequiredService <IBus>().CreateRequestClient <Message>());

            services.AddSingleton <IHostedService, BusService>();
        }
Пример #17
0
        public static IServiceCollection AddHandler <TEventMessage, TInterface, TImpplimentationClass>(this IServiceCollection services)
            where TEventMessage : EventMessage
            where TInterface : class, IEventHandler <TEventMessage>
            where TImpplimentationClass : class, TInterface

        {
            if (string.IsNullOrEmpty(_hostName))
            {
                throw new InvalidOperationException("Must Set Host Name before adding Handler");
            }

            var queueName = $"{_hostName}_{typeof(TEventMessage).Name}";

            services.AddTransient <TInterface, TImpplimentationClass>();
            services.AddTransient(provider => provider.GetRequiredService <IBus>().CreateRequestClient <TEventMessage>());
            _addEndpointAndConsumerActionList.Add((provider, cfg, host) =>
            {
                cfg.ReceiveEndpoint(queueName, e =>
                {
                    e.PrefetchCount = 16;
                    e.UseMessageRetry(x => x.Interval(2, 1000));
                    e.Consumer(() =>
                    {
                        var handlerImplementation = provider.GetRequiredService <TInterface>();
                        return(new TransitConsumer <TEventMessage>(handlerImplementation));
                    });
                    EndpointConvention.Map <TEventMessage>(e.InputAddress);
                });
            });

            return(services);
        }
Пример #18
0
        public async Task Should_contain_the_same_payloads()
        {
            EndpointConvention.Map <B>(InputQueueAddress);

            var sendObserver = new TestSendObserver(TimeSpan.FromSeconds(3));

            using (Bus.ConnectSendObserver(sendObserver))
            {
                await InputQueueSendEndpoint.Send(new A());

                ISentMessage <A> a = sendObserver.Messages.Select <A>().FirstOrDefault();
                ISentMessage <B> b = sendObserver.Messages.Select <B>().FirstOrDefault();

                a.ShouldNotBeNull();
                b.ShouldNotBeNull();

                Dictionary <string, object> ah = a.Context.Headers.GetAll().ToDictionary(x => x.Key, x => x.Value);
                Dictionary <string, object> bh = b.Context.Headers.GetAll().ToDictionary(x => x.Key, x => x.Value);

                ah.ShouldContainKey("x-send-filter");
                ah.ShouldContainKey("x-send-message-filter");
                ah["x-send-filter"].ShouldBe("send-filter");
                ah["x-send-message-filter"].ShouldBe("send-message-filter");

                bh.ShouldContainKey("x-send-filter");
                bh.ShouldContainKey("x-send-message-filter");

                // those fails, as while they DO have ",has-consume-context" they don't have access to SomePayload
                bh["x-send-filter"].ShouldBe("send-filter,has-consume-context,has-some-payload:hello");
                bh["x-send-message-filter"].ShouldBe("send-message-filter,has-consume-context,has-some-payload:hello");
            }
        }
Пример #19
0
        private void BtnConnectRabbitMq_Click(object sender, EventArgs e)
        {
            var address  = txtRabbitMqAddress.Text.EndsWith("/") ? txtRabbitMqAddress.Text : txtRabbitMqAddress.Text + "/";
            var userName = txtRabbitMqUsername.Text;
            var passwrod = txtRabbitMqPassword.Text;

            if (string.IsNullOrEmpty(address) || string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(passwrod))
            {
                MessageBox.Show("请输入正确的数据!");
                return;
            }

            try
            {
                _bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    var host = cfg.Host(new Uri(address), h =>
                    {
                        h.Username(userName);
                        h.Password(passwrod);
                    });
                });

                var endpointUri = new Uri(address + BizSystemNotifyMsg.RabbitMqReceiveEndpointName);

                EndpointConvention.Map <BizSystemNotifyMsg>(endpointUri);

                MessageBox.Show("连接成功");
            }
            catch (Exception ex)
            {
                Debug.Write(ex.ToString());
                MessageBox.Show("启动失败,请检查工作环境");
            }
        }
Пример #20
0
        protected override void ConfigureServicesExt(IServiceCollection services)
        {
            base.ConfigureServicesExt(services);

            services.AddPersistence(Config.Db.ConnectionString);
            services.AddAppFeatureExample();

            services.AddMassTransit(x =>
            {
                // TODO: Register commands recipient endpoints. It's just an example.
                EndpointConvention.Map <ExecuteSomething>(new Uri("queue:api-exchange-something-execution"));

                x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    cfg.Host(Config.RabbitMq.HostUrl, host =>
                    {
                        host.Username(Config.RabbitMq.Username);
                        host.Password(Config.RabbitMq.Password);
                    });

                    cfg.SetLoggerFactory(provider.GetRequiredService <ILoggerFactory>());
                }));

                services.AddHostedService <BusHost>();
            });
        }
        /// <summary>
        /// Add event bus service (RabbitMQ-based).
        /// </summary>
        /// <param name="services">DI Container.</param>
        /// <param name="configuration">Application configuration.</param>
        /// <param name="environment">Hosting environment.</param>
        /// <returns>Configured event bus service.</returns>
        public static IServiceCollection AddEventBusService(this IServiceCollection services,
                                                            IConfiguration configuration,
                                                            IHostEnvironment environment)
        {
            var eventBusSettingsSection = configuration.GetSection("EventBusSettings");
            var eventBusSettings        = eventBusSettingsSection.Get <EventBusSettings>();

            var busControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var hostName = environment.IsProduction() ? eventBusSettings.DockerHostName : eventBusSettings.HostName;
                cfg.Host(hostName, eventBusSettings.VirtualHostName, host =>
                {
                    host.Username(eventBusSettings.UserName);
                    host.Password(eventBusSettings.Password);
                });

                cfg.PropagateOpenTracingContext();

                var queueUri = new Uri(string.Concat("queue:", eventBusSettings.DataProcessingQueue));
                EndpointConvention.Map <IProcessData>(queueUri);
            });

            services.AddSingleton(busControl);

            services.AddSingleton <IPublishEndpoint>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <ISendEndpointProvider>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>());

            services.AddScoped(typeof(ICommandProducer <IProcessData, IRecordDTO>), typeof(ProcessDataProducer));

            return(services);
        }
Пример #22
0
        public void ConfigureServices(IServiceCollection services)
        {
            RabbitConfig rabbitConfig = Configuration.GetSection("RabbitConfig").Get <RabbitConfig>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddMassTransit(x =>
            {
                x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    IRabbitMqHost host = cfg.Host(new Uri($"rabbitmq://{rabbitConfig.Host}/"), h =>
                    {
                        h.Username(rabbitConfig.User);
                        h.Password(rabbitConfig.Password);
                    });

                    EndpointConvention.Map <IBusMessageCommand>(new Uri($"rabbitmq://localhost/{rabbitConfig.InitializeQueue}"));
                }));
            });

            services.AddScoped(provider => provider.GetRequiredService <IBus>()
                               .CreateRequestClient <IBusMessageCommand>());

            services.AddSingleton <Microsoft.Extensions.Hosting.IHostedService, BusService>();
        }
Пример #23
0
        private static ServiceProvider ConfigureServiceProvider()
        {
            var services = new ServiceCollection();

            services.AddSingleton(typeof(MessageCounter2));

            services.AddLogging(b => b.SetMinimumLevel(LogLevel.Trace).AddSerilog());

            EndpointConvention.Map <InitProcess>(new Uri("queue:init-process"));
            EndpointConvention.Map <DoWork>(new Uri("queue:do-work"));
            EndpointConvention.Map <DoSomeExtraWork>(new Uri("queue:do-some-extra-work"));

            services.AddMassTransit(cfg =>
            {
                cfg.SetEndpointNameFormatter(KebabCaseEndpointNameFormatter.Instance);

                cfg.AddConsumers(Assembly.GetExecutingAssembly());

                cfg.UsingRabbitMq(ConfigureBus);
            });

            var provider = services.BuildServiceProvider();

            return(provider);
        }
Пример #24
0
 public void Map()
 {
     EndpointConvention.Map <CreateAccount>(new Uri(HOST_NAME + ACCOUNT_QUEUE_NAME));
     //EndpointConvention.Map<CreditAccount>(new Uri(HOST_NAME + ACCOUNT_QUEUE_NAME));
     //EndpointConvention.Map<DebitAccount>(new Uri(HOST_NAME + ACCOUNT_QUEUE_NAME));
     //EndpointConvention.Map<TransferFunds>(new Uri(HOST_NAME + ACCOUNT_QUEUE_NAME));
 }
Пример #25
0
        public static IServiceCollection AddMq(this IServiceCollection services, MqConfiguration config)
        {
            services.AddMassTransit(x =>
            {
                x.AddConsumer <ScreenshotRequestConsumer>();

                x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    var host = cfg.Host(config.Host, "/", h => { });

                    cfg.ReceiveEndpoint(host, config.ScreenshotRequestEndpoint, e =>
                    {
                        e.PrefetchCount = 16;
                        //e.UseMessageRetry(x => x.Interval(2, 100));
                        e.Consumer <ScreenshotRequestConsumer>(provider);
                    });

                    EndpointConvention.Map <ScreenshotSaved>(host.Address.AppendToPath(config.ScreenshotSavedEndpoint));
                    EndpointConvention.Map <DownloadScreenshots>(host.Address.AppendToPath(config.ScreenshotRequestEndpoint));
                }));
            });

            services.AddHostedService <BusService>();

            return(services);
        }
Пример #26
0
        private static ServiceProvider ConfigureServiceProvider()
        {
            var services = new ServiceCollection();

            services.AddLogging(b => b.SetMinimumLevel(LogLevel.Trace).AddSerilog());

            EndpointConvention.Map <DoWork>(new Uri("queue:test-queue"));

            services.AddMassTransit(x =>
            {
                x.AddConsumers(Assembly.GetExecutingAssembly());

                x.AddBus(provider => Bus.Factory.CreateUsingInMemory(cfg =>
                {
                    cfg.ReceiveEndpoint("test-queue", x =>
                    {
                        x.UseInMemoryOutbox();
                        x.ConfigureConsumers(provider);
                    });
                }));
            });

            var provider = services.BuildServiceProvider();

            return(provider);
        }
Пример #27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddScoped <GetUsersInfoRequestHandler>();
            services.AddScoped <AddUserRequestHandler>();
            services.AddScoped <IUserInfoService, UserInfoService>();

            services.AddScoped <AddUserConsumer>();
            services.AddMassTransit(x =>
            {
                x.AddConsumer <AddUserConsumer>();
                x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    var host = cfg.Host("localhost", "/", h => { });

                    cfg.ReceiveEndpoint(host, "add-user", e =>
                    {
                        e.PrefetchCount = 16;

                        e.ConfigureConsumer <AddUserConsumer>(provider);
                        EndpointConvention.Map <AddUserCommand>(e.InputAddress);
                    });
                }));

                x.AddRequestClient <AddUserCommand>();
            });

            services.AddSingleton <IHostedService, BusService>();
        }
Пример #28
0
        protected override void ConfigureInMemoryBus(IInMemoryBusFactoryConfigurator configurator)
        {
            base.ConfigureInMemoryBus(configurator);

            _machine = new RequestStateMachine();

            configurator.ReceiveEndpoint("request-state", endpoint =>
            {
                var partitioner = endpoint.CreatePartitioner(128);

                endpoint.StateMachineSaga(_machine, new InMemorySagaRepository <RequestState>(), x =>
                {
                    x.Message <RequestStarted>(m => m.UsePartitioner(partitioner, p => p.Message.CorrelationId));
                    x.Message <RequestCompleted>(m => m.UsePartitioner(partitioner, p => p.Message.CorrelationId));
                    x.Message <RequestFaulted>(m => m.UsePartitioner(partitioner, p => p.Message.CorrelationId));
                });
            });

            configurator.ReceiveEndpoint("short-link-service", endpoint =>
            {
                endpoint.Consumer <ShortLinkConsumer>();

                EndpointConvention.Map <RequestShortLink>(endpoint.InputAddress);
            });
        }
Пример #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Dependency Injection
            services.AddScoped <GetCoursesInfoRequestHandler>();
            services.AddScoped <AddCourseInfoRequestHandler>();
            services.AddScoped <GetAllCoursesInfoRequestHandler>();
            services.AddScoped <UpdateCourseInfoRequestHandler>();
            services.AddScoped <DeleteCourseInfoRequestHandler>();
            services.AddScoped <ICourseInfoService, CourseInfoService>();

            // Bus configuration
            services.AddScoped <UpdateCourseInfoMessageHandler>();
            services.AddMassTransit(c =>
            {
                c.AddConsumer <UpdateCourseInfoMessageHandler>();
            });


            services.AddSingleton(provider => MassTransit.Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host("localhost", "/", h => { });

                cfg.ReceiveEndpoint(host, "UpdatingCourseQueue", e =>
                {
                    e.PrefetchCount = 16;
                    e.LoadFrom(provider);
                    EndpointConvention.Map <UpdateMessage>(e.InputAddress);
                });
            }));

            services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <IHostedService, BusService>();
        }
Пример #30
0
        public override void RegisMassTransit(IServiceCollection services)
        {
            services.AddSingleton <ConsumeObserver>();

            services.AddMassTransit(x =>
            {
                x.AddConsumer <ProductMessageConsumerTest>();

                x.AddBus(provider => Bus.Factory.CreateUsingInMemory(cfg =>
                {
                    cfg.Host.ConnectConsumeObserver(services.BuildServiceProvider().GetService <ConsumeObserver>());
                    cfg.ReceiveEndpoint("order_processing", ep =>
                    {
                        ep.ConfigureConsumer <ProductMessageConsumerTest>(provider);
                    });

                    cfg.ConfigureEndpoints(provider);
                }));
            });
            services.AddSingleton <IHostedService, BusService>();

            EndpointConvention.Map <SubmitProduct>(new Uri("loopback://localhost/order_processing"));
            //services.AddSingleton<IPublishEndpoint>(bus);
            //services.AddSingleton<ISendEndpointProvider>(bus);
            //services.AddSingleton<IBus>(bus);
        }
Пример #31
0
 public void Setup()
 {
     _graph = Behavior.BuildGraph().AddActionsInThisNamespace();
     _endpointConvention = new EndpointConvention();
 }