private static void InjectPersistenceServiceSpecificConfiguration(BusFactory busFactory, AppSettingsConfiguration configuration) { busFactory.ConfigureContainer(c => { c.ForSingletonOf <IPersistenceConfiguration>().Use(configuration); // TODO: Add InMemoryStorage c.ForSingletonOf <IStorage>().Use <CqlStorage>(); c.ForSingletonOf <IMessageReplayerRepository>().Use <MessageReplayerRepository>(); c.ForSingletonOf <IMessageReplayer>().Use <MessageReplayer>(); c.ForSingletonOf <IMessageDispatcher>().Use(typeof(Func <IContext, MessageDispatcher>).Name, ctx => { var dispatcher = ctx.GetInstance <MessageDispatcher>(); dispatcher.ConfigureHandlerFilter(x => x != typeof(PeerDirectoryClient)); return(dispatcher); }); c.ForSingletonOf <ITransport>().Use <QueueingTransport>().Ctor <ITransport>().Is <ZmqTransport>(); c.ForSingletonOf <IInMemoryMessageMatcher>().Use <InMemoryMessageMatcher>(); c.Forward <IInMemoryMessageMatcher, IProvideQueueLength>(); c.ForSingletonOf <IStoppingStrategy>().Use <PersistenceStoppingStrategy>(); c.ForSingletonOf <IReporter>().Use <NoopReporter>(); // Cassandra specific c.ForSingletonOf <PeerStateRepository>().Use <PeerStateRepository>(); c.ForSingletonOf <CassandraCqlSessionManager>().Use(() => CassandraCqlSessionManager.Create()); c.Forward <PeerStateRepository, IPeerStateRepository>(); c.ForSingletonOf <ICqlPersistenceConfiguration>().Use <CassandraAppSettingsConfiguration>(); }); }
public static void Main() { Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; _cancelKeySignal.Set(); }; XmlConfigurator.ConfigureAndWatch(new FileInfo(PathUtil.InBaseDirectory("log4net.config"))); _log.Info("Starting in memory directory"); var busFactory = new BusFactory(); InjectDirectoryServiceSpecificConfiguration(busFactory); busFactory .WithConfiguration(new AppSettingsBusConfiguration(), ConfigurationManager.AppSettings["Environment"]) .WithScan() .WithEndpoint(ConfigurationManager.AppSettings["Endpoint"]) .WithPeerId(ConfigurationManager.AppSettings["PeerId"]); using (busFactory.CreateAndStartBus()) { _log.Info("In memory directory started"); _log.Info("Starting dead peer detector"); var deadPeerDetector = busFactory.Container.GetInstance <IDeadPeerDetector>(); deadPeerDetector.Start(); _cancelKeySignal.WaitOne(); _log.Info("Stopping dead peer detector"); deadPeerDetector.Stop(); } }
private static void LoadMassTransitImplementation( Container container, IEnumerable <KeyValuePair <Type, Func <object> > > commandConsumers, IEnumerable <KeyValuePair <Type, Func <object> > > eventConsumers) { var factory = new BusFactory(container.GetInstance); container.RegisterSingle <IBusFactory>(() => factory); Action <ServiceBusConfigurator> config = sbc => sbc.UseRabbitMq(); factory.InitCommanding(commandConsumers, config); factory.InitEventing(eventConsumers, config); container.RegisterSingle <IEventBus, EventBus>(); container.RegisterSingle <ICommandBus, CommandBus>(); container.RegisterSingleDecorator(typeof(ICommandBus), typeof(MassTransitCommandBusDecorator)); container.RegisterWithContext( context => { if (context.ImplementationType == typeof(CommandBus)) { return(factory.ResponseQueue()); } return(factory.ReadModelQueue()); }); }
public static ILifetimeScope CreateLifetimeScope() { var builder = new ContainerBuilder(); //what it does behind is that it uses RabbitHutch.CreateBus() and takes the rabbit_mq connection string; IBus bus = BusFactory.CreateBus(); //here inside startup module are registered other services/components with extension methods like RegisterDatabaseContext and RegisterAutoMapper //also here the SettingsActionsBO are registered //and the settings facade as InstancePerLifetimeScope ////builder.RegisterModule(new StartUpModule()); //In some cases, you may want to pre-generate an instance of an object and add it to the container for use by registered components builder.RegisterInstance(bus).As <IBus>(); //register the setting ms itself, it is in different project ////builder.RegisterType<SettingsMicroservice>().As<IMicroservice>(); var container = builder.Build(); return(container); }
public static IApplicationBuilder InitalizeBus(this IApplicationBuilder app, IConfiguration configuration, IApplicationLifetime lifetime) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (lifetime == null) { throw new ArgumentNullException(nameof(lifetime)); } var busControl = BusFactory.CreateBus(configuration, busConfigurator => { busConfigurator.ReceiveEndpoint("Soloco.RealTimeWeb", endpointConfiguration => { endpointConfiguration.Consumer(() => new VehicleMonitoConsumer()); }); }); if (busControl != null) { var busHandle = busControl.Start(); //todo: handler the bus lifetime by the container lifetime.ApplicationStopping.Register(() => { busHandle.Dispose(); }); } return(app); }
public LoginEventEventHandler(IBackgroundJobManager backgroundJobManager) { _backgroundJobManager = backgroundJobManager; _bus = BusFactory.GetMessageBus(); Logger = NullLogger.Instance; }
private void AddVehicles() { for (int i = 1; i <= 3; i++) { string[] vehicleArgs = Console.ReadLine() .Split(" ", StringSplitOptions.RemoveEmptyEntries); Vehicle vehicle = null; if (i == 1) { vehicle = CarFactory.CreateCar(vehicleArgs); } else if (i == 2) { vehicle = TruckFactory.CreateTruck(vehicleArgs); } else { vehicle = BusFactory.CreateBus(vehicleArgs); } vehicles.Add(vehicle); } }
private static void CreateBus() { VehicleFactory busFactory = new BusFactory(); VehicleShop busShop = new VehicleShop(busFactory); busShop.ConstructVehicle(); }
private static void InjectDirectoryServiceSpecificConfiguration(BusFactory busFactory, string storageType) { var useCassandraStorage = string.Equals(storageType, "Cassandra", StringComparison.OrdinalIgnoreCase); busFactory.ConfigureContainer(c => { c.AddRegistry <DirectoryRegistry>(); c.ForSingletonOf <IDirectoryConfiguration>().Use <AppSettingsDirectoryConfiguration>(); c.For <IDeadPeerDetector>().Use <DeadPeerDetector>(); c.ForSingletonOf <IPeerRepository>().Use(ctx => useCassandraStorage ? (IPeerRepository)ctx.GetInstance <CqlPeerRepository>() : ctx.GetInstance <MemoryPeerRepository>()); c.ForSingletonOf <PeerDirectoryServer>().Use <PeerDirectoryServer>(); c.ForSingletonOf <IPeerDirectory>().Use(ctx => ctx.GetInstance <PeerDirectoryServer>()); c.ForSingletonOf <IMessageDispatcher>().Use(typeof(Func <IContext, MessageDispatcher>).Name, ctx => { var dispatcher = ctx.GetInstance <MessageDispatcher>(); dispatcher.ConfigureHandlerFilter(x => x != typeof(PeerDirectoryClient)); return(dispatcher); }); // Cassandra specific if (useCassandraStorage) { c.ForSingletonOf <CassandraCqlSessionManager>().Use(() => new CassandraCqlSessionManager()); c.ForSingletonOf <ICassandraConfiguration>().Use <CassandraAppSettingsConfiguration>(); } }); }
static void Main(string[] args) { Console.WriteLine("Server"); var bus = BusFactory.CreateRabbitMq((host, sbc) => { sbc.ReceiveEndpoint(host, "alert_queue", endpoint => { endpoint.Handler <AlertMessage>(async context => { await Console.Out.WriteLineAsync($"Received: {context.Message.Text}"); }); }); }); //Sending our cancelation token to keep starting forever! //As instrcuted here //https://github.com/MassTransit/MassTransit/issues/1158 CancellationTokenSource cancelSource = new CancellationTokenSource(); bus.StartAsync(cancelSource.Token); Console.WriteLine("Press Any key to leave..."); Console.ReadLine(); bus.StopAsync(); Console.ReadKey(); }
static void Main(string[] args) { while (true) { Console.Clear(); Console.WriteLine("WebClient - How many Alerts to send? (X to quit)"); var input = Console.ReadLine(); //Quit! if (input.ToUpper().Equals("X")) { break; } if (int.TryParse(input, out int number)) { for (int i = 1; i <= number; i++) { var alert = new AlertMessage() { Text = "WebClient.Alert " + i }; //Publish BusFactory.SendMessage(alert); Console.WriteLine($"SENT: {alert}"); } } } }
public void should_throw() { var factory = new BusFactory(); factory.Invoking(b => b.Create(cfg => cfg.Route(MessageLabel.Empty))) .ShouldThrow <BusConfigurationException>(); }
/// <summary> /// The main. /// </summary> /// <param name="args"> /// The args. /// </param> // ReSharper disable once UnusedParameter.Local private static void Main(string[] args) { LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(); Params = ConsumerParams.ReadFromAppSettings(); Console.WriteLine("Starting consumer [{0}]...", Params.Endpoint); using (IBus bus = new BusFactory().Create(ConfigureBus, false)) { bus.Start(false); var t = new Timer(10000); // ReSharper disable once AccessToDisposedClosure t.Elapsed += (sender, eventArgs) => ((IBusAdvanced)bus).Panic(); if (Params.Misbehave) { t.Start(); } Console.ReadKey(true); t.Close(); Console.WriteLine("Shutting down consumer [{0}]...", Params.Endpoint); } }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException; Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); var clientName = RabbitMqConfiguration.Instance.ClientServiceName(); try { var busFactory = new BusFactory(RabbitMqConfiguration.Instance.GetConnectionString()); HostFactory.Run(x => { x.Service <QueueWatcher>(sc => { sc.ConstructUsing(() => new ContainerRegistration(busFactory).GetClientQueueWatcher()); sc.WhenStarted(tc => tc.Start()); sc.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.StartAutomatically(); x.SetDescription("Processing Client Queue service"); x.SetDisplayName(clientName); x.SetServiceName(clientName); }); } catch (Exception ex) { logger.Error <Exception>("Error", ex); } finally { logger.Info("Service closing"); } }
public static async Task Main(string[] args) { var bus = BusFactory.CreateForRabbitMq(); await bus.StartAsync(); do { var value = await Task.Run(() => { Console.WriteLine("Enter a message to publish. Enter 'quit' to quit"); return(Console.ReadLine()); }); if (value.Equals("q")) { break; } await bus.Publish(new SomethingHappendEvent { Content = value }); } while (true); await bus.StopAsync(); }
private static void InjectDirectoryServiceSpecificConfiguration(BusFactory busFactory, StorageType storageType) { busFactory.ConfigureContainer(c => { c.AddRegistry <DirectoryRegistry>(); c.ForSingletonOf <IDirectoryConfiguration>().Use <AppSettingsDirectoryConfiguration>(); c.For <IDeadPeerDetector>().Use <DeadPeerDetector>(); c.ForSingletonOf <IPeerRepository>().Use(ctx => GetPeerRepository(storageType, ctx)); c.ForSingletonOf <PeerDirectoryServer>().Use <PeerDirectoryServer>(); c.ForSingletonOf <IPeerDirectory>().Use(ctx => ctx.GetInstance <PeerDirectoryServer>()); c.ForSingletonOf <IMessageDispatcher>().Use(typeof(Func <IContext, MessageDispatcher>).Name, ctx => { var dispatcher = ctx.GetInstance <MessageDispatcher>(); dispatcher.ConfigureHandlerFilter(x => x != typeof(PeerDirectoryClient)); return(dispatcher); }); // Cassandra specific if (storageType == StorageType.Cassandra) { c.ForSingletonOf <CassandraCqlSessionManager>().Use(() => new CassandraCqlSessionManager()); c.ForSingletonOf <ICassandraConfiguration>().Use <CassandraAppSettingsConfiguration>(); } }); }
public WebApi(StatelessServiceContext context, RabbitMqBusSettings rabbitMqSettings) : base(context) { Log.Info("WebApi Service: Created"); _rabbitMqHost = BusFactory.CreateUsingRabbitMq(rabbitMqSettings); _rabbitMqHost.StartBus(); }
private static void RunLocalDispatch() { var bus = new BusFactory() .WithHandlers(typeof(BusPerformanceTests.PerfHandler)) .CreateAndStartInMemoryBus(); Console.WriteLine("Press any key to start"); Console.ReadKey(); var running = true; var runTask = Task.Run(() => { using (DispatchQueue.SetCurrentDispatchQueueName(DispatchQueueNameScanner.DefaultQueueName)) using (MessageContext.SetCurrent(MessageContext.CreateTest())) { while (running) { bus.Send(new BusPerformanceTests.PerfCommand(42)); } } }); Console.WriteLine("Press any key to exit"); Console.ReadKey(); running = false; runTask.Wait(); bus.Stop(); }
public RabbitMqRegistry() { var rabbitBuses = RabbitMqHostsConfiguration.Instance; For <IBus>().Singleton().Use(BusFactory.CreateBus(rabbitBuses.DefaultHost)); For <IBootstrapSubcribers>().Singleton().Use <BootstrapSubcribers>(); For <IMessageBus>().Singleton().Use <RabbitMessageBus>(); }
public void OneTimeSetUp() { _container = new Container(configuration => configuration.AddRegistry <BusRegistry>()); _bus = BusFactory.Create("TestE2E", "tcp://localhost:8080", "tcp://localhost:8080", _container); _directoryRepository = _container.GetInstance <IPeerRepository>(); }
public static IBus CreateAndStartInMemoryBus(this BusFactory busFactory, TestPeerDirectory directory, ITransport transport) { return(busFactory.WithConfiguration("in-memory-bus", "Memory") .ConfigureContainer(cfg => { cfg.ForSingletonOf <IPeerDirectory>().Use(directory); cfg.ForSingletonOf <ITransport>().Use(transport); }).CreateAndStartBus()); }
static void Main(string[] args) { Console.WriteLine("(WebClient) Listening..."); while (true) { BusFactory.Listen <AlertMessage>((payload, response) => { Console.WriteLine($"RECEIVED@{response.routing_key}: {payload}"); }); } }
protected override void Run(CancellationToken cancellationToken) { var busFactory = new BusFactory(_container).WithScan() .WithConfiguration("tcp://localhost:129", "Demo") .WithPeerId("Receiver.*"); using (busFactory.CreateAndStartBus()) { cancellationToken.WaitHandle.WaitOne(); } }
public void should_throw_on_validation() { IBus bus = null; Action busInitializationAction = () => { bus = new BusFactory().Create(cfg => cfg.Route("something")); }; busInitializationAction.ShouldThrow<BusConfigurationException>(); if (bus != null) { bus.Shutdown(); } }
public void should_throw_on_validation() { IBus bus = null; Action busInitializationAction = () => { bus = new BusFactory().Create(cfg => cfg.Route("something")); }; busInitializationAction.ShouldThrow <BusConfigurationException>(); if (bus != null) { bus.Shutdown(); } }
public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IDocumentStoreHolder>(new DocumentStoreHolder("{Raven db endpoint}")); services.AddTransient <IPeopleRepository, PeopleRepository>(); var azureStringConnection = "Endpoint={your namespace for azure service bus}/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey={Access key of RootManageSharedAccessKey}"; var bus = BusFactory .CreateSendOnly(azureStringConnection); services.AddSingleton(bus); services.AddMvc(); bus.StartAsync(); }
public static ILifetimeScope CreateLifetimeScope() { var builder = new ContainerBuilder(); var bus = BusFactory.CreateBus(); builder.RegisterModule(new StartUpModule()); builder.RegisterInstance(bus).As <IBus>(); builder.RegisterType <OrderMicroservice>().As <IMicroservice>(); return(builder.Build()); }
static void Main(string[] args) { var channel = BusFactory.SetupChannel(); //Configure TOPIC! BusFactory.SetupTopic(channel); Console.WriteLine("Server Up and running..."); BusFactory.Listen <AlertMessage>((data, ea) => { Console.WriteLine($"RECEIVED@{ea.RoutingKey}: {data}"); }); }
public async Task Message_should_be_retried_five_times() { retries = 0; var bus = BusFactory.Address("test") .UseTestBroker() .CreateBus(); bus.Start().Wait(); await bus.Send("test", new TestMessage { ThrowError = true }); Assert.Equal(5, retries); }
public static void Send <T>(this T message, bool onCallback = false, string contextName = null) where T : class, ISpecializedMessage { if (message == null) { return; } using (var ctx = BusFactory.CreateBusContext()) { SendInternal(ctx, message, onCallback, contextName); } }
public void OneTimeSetUp() { var container = new Container(configuration => configuration.AddRegistry <BusRegistry>()); _directory = container.GetInstance <IPeerDirectory>(); container.Configure((conf) => { conf.For <ITransport>().Use <TestBusTransport>(); }); _bus = BusFactory.Create("TestE2E", "tcp://localhost:8080", "tcp://localhost:8080", container); }
/// <summary> /// Создает и конфигурирует конечную точку шины сообщений. /// Конечная точка автоматически удаляется после выполнения теста. /// </summary> /// <param name="name">Имя конечной точки.</param> /// <param name="configureAction">Указатель на метод конфигурирования конечной точки.</param> /// <param name="shouldStart"><c>true</c> - если конечная точка должна запуститься сразу после создания.</param> /// <returns>Созданная конечная точка.</returns> protected IBus ConfigureBus(string name, Action<IBusConfigurator> configureAction, bool shouldStart = false) { IBus bus = new BusFactory().Create( c => { c.UseRabbitMq(); c.SetEndpoint(name); c.SetConnectionString(this.amqpConnection + this.vhostName); configureAction(c); }, shouldStart); this.endpoints.Add(bus); return bus; }