예제 #1
0
파일: Program.cs 프로젝트: Red-F/Paramore
        static void Main()
        {
            var container = new TinyIoCContainer();


            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            var messageStore = new InMemoryMessageStore();

            var messagingConfiguration = new MsSqlMessagingGatewayConfiguration(@"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
            var producer = new MsSqlMessageProducer(messagingConfiguration);

            var builder = CommandProcessorBuilder.With()
                          .Handlers(new HandlerConfiguration())
                          .DefaultPolicy()
                          .TaskQueues(new MessagingConfiguration((IAmAMessageStore <Message>)messageStore, producer, messageMapperRegistry))
                          .RequestContextFactory(new InMemoryRequestContextFactory());

            var commandProcessor = builder.Build();

            commandProcessor.Post(new GreetingEvent("Ian"));
        }
예제 #2
0
        static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var serviceCollection = new ServiceCollection();

            var messagingConfiguration = new MsSqlMessagingGatewayConfiguration(@"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
            var producer = new MsSqlMessageProducer(messagingConfiguration);

            serviceCollection.AddBrighter(options =>
            {
                var outBox = new InMemoryOutbox();
                options.BrighterMessaging = new BrighterMessaging(outBox, outBox, producer, null);
            }).AutoFromAssemblies();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var commandProcessor = serviceProvider.GetService <IAmACommandProcessor>();


            commandProcessor.Post(new GreetingEvent("Ian"));
        }
예제 #3
0
파일: Program.cs 프로젝트: camilleri/cqrs
        private static CommandProcessor BuildCommandProcessor()
        {
            var messageStore = new InMemoryMessageStore();

            var container             = new UnityContainer();
            var messageMapperFactory  = new UnityMessageMapperFactory(container);
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            var connectionString = @"Database=BrighterSqlQueue;Server=localhost;Integrated Security=SSPI;";
            var gatewayConfig    = new MsSqlMessagingGatewayConfiguration(connectionString, "QueueData");
            var producer         = new MsSqlMessageProducer(gatewayConfig);

            var builder = CommandProcessorBuilder.With()
                          .Handlers(new HandlerConfiguration())
                          .DefaultPolicy()
                          .TaskQueues(new MessagingConfiguration((IAmAMessageStore <Message>)messageStore, producer,
                                                                 messageMapperRegistry))
                          .RequestContextFactory(new InMemoryRequestContextFactory());

            var commandProcessor = builder.Build();

            return(commandProcessor);
        }
예제 #4
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="MsSqlMessageQueue{T}" /> class.
 /// </summary>
 /// <param name="configuration"></param>
 public MsSqlMessageQueue(MsSqlMessagingGatewayConfiguration configuration)
 {
     _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
     if (s_logger.IsEnabled(LogLevel.Debug))
     {
         s_logger.LogDebug("MsSqlMessageQueue({ConnectionString}, {QueueStoreTable})", _configuration.ConnectionString, _configuration.QueueStoreTable);
     }
     ContinueOnCapturedContext = false;
 }
예제 #5
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="MsSqlMessageQueue{T}" /> class.
 /// </summary>
 /// <param name="configuration"></param>
 public MsSqlMessageQueue(MsSqlMessagingGatewayConfiguration configuration)
 {
     _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
     if (Logger.Value.IsDebugEnabled())
     {
         Logger.Value.Debug(
             $"MsSqlMessageQueue({_configuration.ConnectionString}, {_configuration.QueueStoreTable})");
     }
     ContinueOnCapturedContext = false;
 }
예제 #6
0
        private static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("usage: MultipleSender <count>");
                Console.WriteLine("eg   : MultipleSender 500");
                return;
            }

            if (!int.TryParse(args[0], out int repeatCount))
            {
                Console.WriteLine($"{args[0]} is not a valid number");
                return;
            }

            var container = new TinyIoCContainer();

            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(CompetingConsumerCommand), typeof(CompetingConsumerCommandMessageMapper) }
            };

            var outbox = new InMemoryOutbox();

            var messagingConfiguration =
                new MsSqlMessagingGatewayConfiguration(
                    @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
            var producer = new MsSqlMessageProducer(messagingConfiguration);

            var builder = CommandProcessorBuilder.With()
                          .Handlers(new HandlerConfiguration())
                          .DefaultPolicy()
                          .TaskQueues(new MessagingConfiguration((IAmAnOutbox <Message>)outbox, producer, messageMapperRegistry))
                          .RequestContextFactory(new InMemoryRequestContextFactory());

            var commandProcessor = builder.Build();

            using (new TransactionScope(TransactionScopeOption.RequiresNew,
                                        new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadCommitted
            },
                                        TransactionScopeAsyncFlowOption.Enabled))
            {
                Console.WriteLine($"Sending {repeatCount} command messages");
                var sequenceNumber = 1;
                for (int i = 0; i < repeatCount; i++)
                {
                    commandProcessor.Post(new CompetingConsumerCommand(sequenceNumber++));
                }
                // We do NOT complete the transaction here to show that a message is
                // always queued, whether the transaction commits or aborts!
            }
        }
예제 #7
0
        private static Dispatcher BuildDispatcher()
        {
            var container      = new UnityContainer();
            var handlerFactory = new UnityHandlerFactory(container);
            // var asyncHandlerFactory = new UnityAsyncHandlerFactory(container);
            var messageMapperFactory = new UnityMessageMapperFactory(container);

            container.RegisterType <IHandleRequests <GreetingEvent>, GreetingEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingEvent, GreetingEventHandler>();
            subscriberRegistry.Register <GreetingCommand, GreetingCommandHandler>();

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            var connectionString       = @"Database=BrighterSqlQueue;Server=localhost;Integrated Security=SSPI;";
            var gatewayConfig          = new MsSqlMessagingGatewayConfiguration(connectionString, "QueueData");
            var messageConsumerFactory = new MsSqlMessageConsumerFactory(gatewayConfig);
            var commandProcessor       = CommandProcessorBuilder.With()
                                         .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                         .DefaultPolicy()
                                         .NoTaskQueues()
                                         .RequestContextFactory(new InMemoryRequestContextFactory())
                                         .Build();
            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(commandProcessor)
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new MsSqlInputChannelFactory(messageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <GreetingEvent>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("greeting.event"),
                    new RoutingKey("greeting.event"),
                    timeoutInMilliseconds: 200)
            }
                                          ).Build();

            container.RegisterInstance <IAmACommandProcessor>(commandProcessor);
            container.RegisterType <IHandleRequests <GreetingCommand>, GreetingCommandHandler>();
            container.RegisterType <MyValidationHandler <GreetingCommand>, GreetingCommandValidationHandler>();
            container.RegisterType <MyPostAuditHandler <GreetingCommand>, GreetingCommandPostAuditHandler>();

            return(dispatcher);
        }
예제 #8
0
        private static async Task Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Warning()
                         .WriteTo.Console()
                         .CreateLogger();

            var host = new HostBuilder()
                       .ConfigureServices((hostContext, services) =>
            {
                var connections = new Connection[]
                {
                    new Connection <CompetingConsumerCommand>(
                        new ConnectionName("paramore.example.multipleconsumer.command"),
                        new ChannelName("multipleconsumer.command"),
                        new RoutingKey("multipleconsumer.command"),
                        timeoutInMilliseconds: 200)
                };

                var messagingConfiguration = new MsSqlMessagingGatewayConfiguration(@"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
                var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration);

                services.AddServiceActivator(options =>
                {
                    options.Connections       = connections;
                    options.ChannelFactory    = new ChannelFactory(messageConsumerFactory);
                    var outBox                = new InMemoryOutbox();
                    options.BrighterMessaging = new BrighterMessaging(outBox, outBox, new MsSqlMessageProducer(messagingConfiguration), null);
                }).AutoFromAssemblies();


                services.AddHostedService <ServiceActivatorHostedService>();
                services.AddHostedService <RunStuff>();

                services.AddSingleton <IAmACommandCounter, CommandCounter>();
            })

                       .UseConsoleLifetime()
                       .UseSerilog()
                       .Build();

            await host.RunAsync();
        }
예제 #9
0
        public static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var host = new HostBuilder()
                       .ConfigureServices((hostContext, services) =>

            {
                var subscriptions = new Subscription[]
                {
                    new Subscription <GreetingEvent>(
                        new SubscriptionName("paramore.example.greeting"),
                        new ChannelName("greeting.event"),
                        new RoutingKey("greeting.event"),
                        timeoutInMilliseconds: 200)
                };

                //create the gateway
                var messagingConfiguration =
                    new MsSqlMessagingGatewayConfiguration(
                        @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
                var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration);
                services.AddServiceActivator(options =>
                {
                    options.Subscriptions     = subscriptions;
                    options.ChannelFactory    = new ChannelFactory(messageConsumerFactory);
                    var outBox                = new InMemoryOutbox();
                    options.BrighterMessaging = new BrighterMessaging(outBox, outBox, new MsSqlMessageProducer(messagingConfiguration), null);
                }).AutoFromAssemblies();


                services.AddHostedService <ServiceActivatorHostedService>();
            })
                       .UseConsoleLifetime()
                       .UseSerilog()
                       .Build();

            await host.RunAsync();
        }
예제 #10
0
        private static async Task Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("usage: MultipleSender <count>");
                Console.WriteLine("eg   : MultipleSender 500");
                return;
            }

            if (!int.TryParse(args[0], out int repeatCount))
            {
                Console.WriteLine($"{args[0]} is not a valid number");
                return;
            }

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var host = new HostBuilder()
                       .ConfigureServices((hostContext, services) =>
            {
                //create the gateway
                var messagingConfiguration = new MsSqlMessagingGatewayConfiguration(@"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");

                services.AddBrighter(options =>
                {
                    var outBox = new InMemoryOutbox();
                    options.BrighterMessaging = new BrighterMessaging(outBox, new MsSqlMessageProducer(messagingConfiguration));
                }).AutoFromAssemblies();

                services.AddHostedService <RunCommandProcessor>(provider => new RunCommandProcessor(provider.GetService <IAmACommandProcessor>(), repeatCount));
            })
                       .UseConsoleLifetime()
                       .UseSerilog()
                       .Build();

            await host.RunAsync();
        }
예제 #11
0
        private static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Warning()
                         .WriteTo.LiterateConsole()
                         .CreateLogger();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IAmACommandCounter, CommandCounter>();
            container.Register <IHandleRequests <CompetingConsumerCommand>, CompetingConsumerCommandHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <CompetingConsumerCommand, CompetingConsumerCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(CompetingConsumerCommand), typeof(CompetingConsumerCommandMessageMapper) }
            };

            //create the gateway
            var messagingConfiguration =
                new MsSqlMessagingGatewayConfiguration(
                    @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
            var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration);

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(CommandProcessorBuilder.With()
                                               .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                               .Policies(policyRegistry)
                                               .NoTaskQueues()
                                               .RequestContextFactory(new InMemoryRequestContextFactory())
                                               .Build())
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new MsSqlInputChannelFactory(messageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <CompetingConsumerCommand>(
                    new ConnectionName("paramore.example.multipleconsumer.command"),
                    new ChannelName("multipleconsumer.command"),
                    new RoutingKey("multipleconsumer.command"),
                    timeoutInMilliseconds: 200)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press Enter to stop receiving ...");
            Console.ReadLine();

            dispatcher.End().Wait();

            var count = container.Resolve <IAmACommandCounter>().Counter;


            Console.WriteLine($"There were {count} commands handled by this consumer");
            Console.WriteLine("Press Enter to exit ...");
            Console.ReadLine();
        }
예제 #12
0
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingEvent>, GreetingEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingEvent, GreetingEventHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            //create the gateway
            var messagingConfiguration =
                new MsSqlMessagingGatewayConfiguration(
                    @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
            var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration);

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(CommandProcessorBuilder.With()
                                               .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                               .Policies(policyRegistry)
                                               .NoTaskQueues()
                                               .RequestContextFactory(new InMemoryRequestContextFactory())
                                               .Build())
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new ChannelFactory(messageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <GreetingEvent>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("greeting.event"),
                    new RoutingKey("greeting.event"),
                    timeoutInMilliseconds: 200)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press Enter to stop ...");
            Console.ReadLine();

            dispatcher.End().Wait();
        }