protected override void SetUp() { _activator = Using(new BuiltinHandlerActivator()); _waitedSeconds = new ConcurrentQueue<double>(); _rebusConfigurer = Configure.With(_activator) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "test backoff")) .Options(o => { o.SetBackoffTimes(TimeSpan.FromSeconds(0.2), TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(1)); o.Decorate<ITransport>(c => { var transport = c.Get<ITransport>(); var transportTap = new TransportTap(transport); transportTap.NoMessageReceived += () => { var elapsedSinceStart = DateTime.UtcNow - _busStartTime; var elapsedSeconds = Math.Round(elapsedSinceStart.TotalSeconds, 1); _waitedSeconds.Enqueue(elapsedSeconds); }; return transportTap; }); o.SetMaxParallelism(10); o.SetNumberOfWorkers(1); }); }
static void Main() { using (var adapter = new BuiltinHandlerActivator()) { adapter.Handle<Reply>(async reply => { Console.WriteLine("Got reply '{0}' (from OS process {1})", reply.KeyChar, reply.OsProcessId); }); Configure.With(adapter) .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn)) .Transport(t => t.UseSqlServer("server=.; database=rebus; trusted_connection=true", "Messages", "producer.input")) .Routing(r => r.TypeBased().MapAssemblyOf<Job>("consumer.input")) .Start(); Console.WriteLine("Press Q to quit or any other key to produce a job"); while (true) { var keyChar = char.ToLower(Console.ReadKey(true).KeyChar); switch (keyChar) { case 'q': goto quit; default: adapter.Bus.Send(new Job(keyChar)).Wait(); break; } } quit: Console.WriteLine("Quitting..."); } }
protected override void SetUp() { var network = new InMemNetwork(); _events = new ConcurrentQueue<string>(); _uowActivator = new BuiltinHandlerActivator(); _otherActivator = new BuiltinHandlerActivator(); Using(_uowActivator); Using(_otherActivator); _uowBus = Configure.With(_uowActivator) .Logging(l => l.Console(LogLevel.Warn)) .Transport(t => t.UseInMemoryTransport(network, UowQueueName)) .Options(o => { o.EnableUnitOfWork(c => _events, commitAction: (c, e) => RegisterEvent("uow committed"), rollbackAction: (c, e) => RegisterEvent("uow rolled back"), cleanupAction: (c, e) => RegisterEvent("uow cleaned up")); o.SimpleRetryStrategy(maxDeliveryAttempts: 1); //o.LogPipeline(true); }) .Start(); Configure.With(_otherActivator) .Logging(l => l.Console(LogLevel.Warn)) .Transport(t => t.UseInMemoryTransport(network, OtherQueueName)) .Start(); }
public async Task ItHasBeenFixed() { var activator = new BuiltinHandlerActivator(); Using(activator); var receivedMessageIds = new ConcurrentBag<string>(); activator.Handle<string>(async (_, context, message) => { receivedMessageIds.Add(context.TransportMessage.Headers[Headers.MessageId]); }); var bus = Configure.With(activator) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "buggerino")) .Start(); var customHeaders = new Dictionary<string, string> { {"custom-header", "woohoo"} }; const string repeatedMessage = "hej med dig"; await bus.SendLocal(repeatedMessage, customHeaders); await bus.SendLocal("hej igen med", customHeaders); await bus.SendLocal(repeatedMessage, customHeaders); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.That(receivedMessageIds.Distinct().Count(), Is.EqualTo(3), "Expected three unique message IDs - got: {0}", string.Join(", ", receivedMessageIds)); }
protected override void SetUp() { using (var transport = new RabbitMqTransport(ConnectionString, _receiverQueueName, new NullLoggerFactory())) { transport.PurgeInputQueue(); } _receiver = new BuiltinHandlerActivator(); Using(_receiver); Configure.With(_receiver) .Logging(l => l.Console(LogLevel.Info)) .Transport(t => t.UseRabbitMq(ConnectionString, _receiverQueueName).Prefetch(1)) .Options(o => { o.SetNumberOfWorkers(1); o.SetMaxParallelism(1); }) .Start(); _sender = Configure.With(new BuiltinHandlerActivator()) .Logging(l => l.Console(LogLevel.Info)) .Transport(t => t.UseRabbitMqAsOneWayClient(ConnectionString)) .Routing(r => r.TypeBased().MapFallback(_receiverQueueName)) .Start(); Using(_sender); }
static void Main(string[] args) { using (var activator = new BuiltinHandlerActivator()) { var bus = Configure.With(activator) .Transport(t => t.UseFileSystem(messageQueueFilePath, "rebusStarbucks.cashier")) //.Transport(t => t.UseMsmq("rebusStarbucks.cashier")) //.Transport(t => { t.Register(context => new Msmq.MsmqTransport("rebusStarbucks.cashier", true)); }) .Routing(r => { r.TypeBased() .Map<PaymentDueMessage>("rebusStarbucks.client") .Map<NewOrderMessage>("rebusStarbucks.client") .Map<PaymentCompleteMessage>("rebusStarbucks.barista"); }) .Options(op => { op.SetMaxParallelism(1).EnableEncryption("VW6DcqJioLHnV1b9oPnDFCYAGB7VxJcY"); }) .Sagas(x => x.StoreInJsonFile(AppDomain.CurrentDomain.BaseDirectory)) .Start(); activator.Bus.Subscribe<NewOrderMessage>(); activator.Register(() => new CashierSaga(bus)); Console.ReadLine(); } }
public void LooksGood() { using (var activator = new BuiltinHandlerActivator()) { Console.WriteLine(ConnectionString); var bus = Configure.With(activator) .Transport(t => t.UseAzureServiceBus(ConnectionString, "contenttypetest")) .Options(o => o.SetNumberOfWorkers(0)) .Start(); bus.Advanced.Workers.SetNumberOfWorkers(0); var message = new RigtigBesked { Text = "hej med dig min ven! DER ER JSON HERI!!!", Embedded = new RigtigEmbedded { Whatever = new[] {1, 2, 3}, Message = "I'm in here!!" } }; bus.SendLocal(message).Wait(); } }
public void DoesNotDispatchMessageWithNullBus() { var busInstances = new ConcurrentQueue<IBus>(); using (var activator = new BuiltinHandlerActivator()) { activator.Handle<string>(async (bus, message) => { busInstances.Enqueue(bus); }); Configure.With(activator) .Logging(l => l.ColoredConsole(LogLevel.Warn)) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "race-condition")) .Options(o => { o.SetNumberOfWorkers(1); o.SetMaxParallelism(1); }) .Start(); Task.WaitAll(Enumerable.Range(0, 1000) .Select(i => activator.Bus.SendLocal($"message-{i}")) .ToArray()); } Thread.Sleep(1000); var numberOfNulls = busInstances.Count(i => i == null); Assert.That(numberOfNulls, Is.EqualTo(0), "Did not expect any messages to be dispatched with a NULL bus instance"); }
public async Task CanReceiveBunchOfMessages() { var events = new ConcurrentQueue<string>(); using (var activator = new BuiltinHandlerActivator()) { activator.Handle<string>(async s => events.Enqueue(s)); Configure.With(activator) .Logging(l => l.Console(minLevel:LogLevel.Info)) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "bimse")) .Options(o => { o.Register<IWorkerFactory>(c => { var transport = c.Get<ITransport>(); var pipeline = c.Get<IPipeline>(); var pipelineInvoker = c.Get<IPipelineInvoker>(); var rebusLoggerFactory = c.Get<IRebusLoggerFactory>(); return new AsyncTaskWorkerFactory(transport, pipeline, pipelineInvoker, rebusLoggerFactory); }); o.SetNumberOfWorkers(100); }) .Start(); var bus = activator.Bus; await Task.WhenAll(Enumerable.Range(0, 100) .Select(i => bus.SendLocal(string.Format("msg-{0}", i)))); await Task.Delay(1000); Assert.That(events.Count, Is.EqualTo(100)); } }
static void Main() { using (var activator = new BuiltinHandlerActivator()) { activator .Register((bus, context) => new TradeCreatedSaga(bus)) .Register(() => new SendInvoiceHandler()) .Register(() => new TakeOutForManualInspectionHandler()); Configure.With(activator) .ConfigureEndpoint(Config.Queues.Billing) .Start(); Task.WaitAll( activator.Bus.Subscribe<TradeCreated>(), activator.Bus.Subscribe<TradeAccepted>(), activator.Bus.Subscribe<TradeRejected>() ); Console.WriteLine("===== Billing ====="); Console.WriteLine("Press ENTER to quit"); Console.ReadLine(); } }
static void Main() { // configure Serilog to log with colors in a fairly compact format Log.Logger = new LoggerConfiguration() .WriteTo.ColoredConsole(outputTemplate: "{Timestamp:HH:mm:ss} {Message}{NewLine}{Exception}") .CreateLogger(); using (var activator = new BuiltinHandlerActivator()) { activator.Register(() => new EventLogger()); var bus = Configure.With(activator) .ConfigureEndpoint(EndpointRole.Subscriber) .Start(); Task.WaitAll( bus.Subscribe<AmountsCalculated>(), bus.Subscribe<TaxesCalculated>(), bus.Subscribe<PayoutMethodSelected>(), bus.Subscribe<PayoutReady>(), bus.Subscribe<PayoutNotReady>() ); Console.WriteLine("Press ENTER to quit"); Console.ReadLine(); } }
public async Task NizzleName() { var gotMessage = new ManualResetEvent(false); using (var activator = new BuiltinHandlerActivator()) { activator.Handle<string>(async s => { Console.WriteLine("Got message: {0}", s); gotMessage.Set(); }); Configure.With(activator) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "bimse")) .Options(o => { o.Register<IWorkerFactory>(c => { var transport = c.Get<ITransport>(); var pipeline = c.Get<IPipeline>(); var pipelineInvoker = c.Get<IPipelineInvoker>(); var rebusLoggerFactory = c.Get<IRebusLoggerFactory>(); return new AsyncTaskWorkerFactory(transport, pipeline, pipelineInvoker, rebusLoggerFactory); }); }) .Start(); await activator.Bus.SendLocal("hej med dig min ven"); gotMessage.WaitOrDie(TimeSpan.FromSeconds(3)); } }
protected override void SetUp() { MsmqUtil.Delete(InputQueueName); _handlerActivator = new BuiltinHandlerActivator(); _bus = Configure.With(_handlerActivator) .Logging(l => l.Console()) .Transport(t => { t.UseMsmq(InputQueueName) .OnCreated(queue => { queue.ResetPermissions(); var user = new SecurityIdentifier(WellKnownSidType.WorldSid, null) .Translate(typeof(NTAccount)) .ToString(); queue.SetPermissions(user, MessageQueueAccessRights.FullControl); }); }) .Routing(r => r.TypeBased().Map<string>(InputQueueName)) .Options(o => o.SetNumberOfWorkers(1)) .Start(); Using(_bus); }
public async Task DoIt() { var builtinHandlerActivator = new BuiltinHandlerActivator(); var allDone = false; var gotMessage = new ManualResetEvent(false); builtinHandlerActivator.Handle<string>(async _ => { gotMessage.Set(); await Task.Delay(2000); allDone = true; }); var bus = Configure.With(builtinHandlerActivator) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "shutdown with pending tasks")) .Start(); using (bus) { await bus.SendLocal("hej"); gotMessage.WaitOrDie(TimeSpan.FromSeconds(2)); // make bus shut down here } Assert.That(allDone, Is.True, "The message was apparently not handled all the way to the end!!!"); }
static void Main() { // serve the web app out of the "site" directory directly in the source code - allows for // quicker edit/reload iterations var webAppBaseDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "site"); using (var activator = new BuiltinHandlerActivator()) { Configure.With(activator) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "owin-test")) .Options(o => { // add the web host o.AddWebHost(ListenUrl, app => { // serve web application out of the configured base directory app.UseFileServer(new FileServerOptions { FileSystem = new PhysicalFileSystem(webAppBaseDir), DefaultFilesOptions = { DefaultFileNames = { "index.html" } } }); // host a simple API app.Map("/api/hello", a => a.Run(GetTimedGreeting)); }); }) .Start(); // invoke default browser and navigate to the URL Process.Start(ListenUrl); Console.WriteLine("Press ENTER to quit"); Console.ReadLine(); } }
public void NumberOfWorkersIsLimitedByMaxParallelism() { var counter = new WorkerCounter(); using (var adapter = new BuiltinHandlerActivator()) { Configure.With(adapter) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "worker-/parallelism-test")) .Options(o => { o.SetMaxParallelism(1); o.SetNumberOfWorkers(10); o.Decorate<IWorkerFactory>(c => { counter.SetWorkerFactory(c.Get<IWorkerFactory>()); return counter; }); }) .Start(); Thread.Sleep(TimeSpan.FromSeconds(1)); } Assert.That(counter.NumberOfWorkersCreated, Is.EqualTo(1)); }
public async Task CanMoveMessageToErrorQueueEvenThoughExceptionIsNotSerializable() { using (var activator = new BuiltinHandlerActivator()) { activator.Handle<string>(async str => { throw new ThisOneCannotBeSerialized("BAM!!!!!!!!!!!11111111111111111"); }); var network = new InMemNetwork(); var bus = Configure.With(activator) .Transport(t => t.UseInMemoryTransport(network, "unserializable exceptions")) .Options(o => o.SimpleRetryStrategy(maxDeliveryAttempts: 1)) .Start(); const string knownString = "JUST SOME LISP!!!!11((((((((((((((((((()))))))))))))))))))))))"; await bus.SendLocal(knownString); var failedMessage = await network.WaitForNextMessageFrom("error"); Assert.That(Encoding.UTF8.GetString(failedMessage.Body), Is.EqualTo(JsonConvert.SerializeObject(knownString))); } }
Tuple<BuiltinHandlerActivator, CountingTransport> StartBus(bool customizeBackoffTimes) { var activator = new BuiltinHandlerActivator(); CountingTransport countingTransport = null; Configure.With(activator) .Logging(l => l.Console(minLevel: LogLevel.Warn)) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "customized-backoff")) .Options(o => { o.Decorate<ITransport>(c => { var transport = c.Get<ITransport>(); countingTransport = new CountingTransport(transport); return countingTransport; }); o.SetNumberOfWorkers(20); o.SetMaxParallelism(20); if (customizeBackoffTimes) { o.SetBackoffTimes( TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(5)); } }) .Start(); return Tuple.Create(activator, countingTransport); }
protected override void SetUp() { _activator = Using(new BuiltinHandlerActivator()); _snitch = new BackoffSnitch(); Configure.With(_activator) .Logging(l => l.Console(LogLevel.Info)) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "busy-test")) .Options(o => { o.SetNumberOfWorkers(1); o.SetMaxParallelism(500); o.SetBackoffTimes(TimeSpan.FromSeconds(0.2)); // install the snitch o.Decorate<ISyncBackoffStrategy>(c => { var syncBackoffStrategy = c.Get<ISyncBackoffStrategy>(); _snitch.SyncBackoffStrategy = syncBackoffStrategy; return _snitch; }); o.Decorate<ITransport>(c => { var transport = c.Get<ITransport>(); return new IntroducerOfLatency(transport, receiveLatencyMs: 10); }); }) .Start(); }
static void Main() { using (var publisher = new BuiltinHandlerActivator()) using (var subscriber1 = new BuiltinHandlerActivator()) using (var subscriber2 = new BuiltinHandlerActivator()) using (var subscriber3 = new BuiltinHandlerActivator()) { ConfigureSubscriber(subscriber1, "endpoint1"); ConfigureSubscriber(subscriber2, "endpoint2"); ConfigureSubscriber(subscriber3, "endpoint3"); subscriber1.Bus.Advanced.Topics.Subscribe("mercedes.#").Wait(); subscriber2.Bus.Advanced.Topics.Subscribe("mercedes.bmw.#").Wait(); subscriber3.Bus.Advanced.Topics.Subscribe("mercedes.bmw.vw").Wait(); var publisherBus = Configure.With(publisher) .Logging(l => l.ColoredConsole(MinimumLogLevel)) .Transport(t => t.UseRabbitMqAsOneWayClient(ConnectionString)) .Start(); var topicsApi = publisherBus.Advanced.Topics; topicsApi.Publish("mercedes.bmw.vw", "This one should be received by all!").Wait(); topicsApi.Publish("mercedes.bmw.mazda", "This one should be received by 1 & 2").Wait(); topicsApi.Publish("mercedes.honda", "This one should be received by 1").Wait(); Console.WriteLine("Press ENTER to quit"); Console.ReadLine(); } }
static void Main() { using (var adapter = new BuiltinHandlerActivator()) { adapter.Handle<Job>(async job => { Console.WriteLine("Processing job {0}", job.JobNumber); await Task.Delay(TimeSpan.FromMilliseconds(300)); }); Configure.With(adapter) .Logging(l => l.ColoredConsole(LogLevel.Warn)) .Transport(t => t.UsePostgreSql("server=localhost;port=5433;database=rebus2_test; user id=test; password=test; maximum pool size=30", "messages", "consumer")) .Options(o => { o.SetNumberOfWorkers(10); o.SetMaxParallelism(20); }) .Start(); Console.WriteLine("Consumer listening - press ENTER to quit"); Console.ReadLine(); } }
static IBus StartBus(InMemNetwork network, string queueName, ConcurrentQueue<string> recordedEvents) { var activator = new BuiltinHandlerActivator(); activator.Handle(async (string message) => { recordedEvents.Enqueue($"GOT MESSAGE: {message}"); }); return Configure.With(activator) .Transport(t => t.UseInMemoryTransport(network, queueName)) .Options(o => { o.Decorate(c => { var events = c.Get<BusLifetimeEvents>(); events.BusStarting += () => recordedEvents.Enqueue("Bus starting"); events.BusStarted += () => recordedEvents.Enqueue("Bus started"); events.BusDisposing += () => recordedEvents.Enqueue("Bus disposing"); events.BusDisposed += () => recordedEvents.Enqueue("Bus disposed"); return events; }); }) .Start(); }
static void Main() { using (var creditAssessmentClient = new HttpClient()) { creditAssessmentClient.BaseAddress = new Uri(Config.CreditAssessmentUrl); using (var activator = new BuiltinHandlerActivator()) { activator.Register((bus, context) => new ConfirmationHandler(bus, creditAssessmentClient)); Configure.With(activator) .ConfigureEndpoint(Config.Queues.Confirmation) .Options(o => { o.SetMaxParallelism(100); }) .Start(); activator.Bus.Subscribe<TradeCreated>().Wait(); Console.WriteLine("===== Confirmation ====="); Console.WriteLine("Press ENTER to quit"); Console.ReadLine(); } } }
public void ItWorksWithComplexMessage(bool withCompressionEnabled) { var activator = new BuiltinHandlerActivator(); var gotIt = new ManualResetEvent(false); activator.Handle<TextMessage>(async str => { if (string.Equals(str.Text, LongText)) { gotIt.Set(); } else { throw new Exception(string.Format("Received text with {0} chars did not match expected text with {1} chars!", str.Text.Length, LongText.Length)); } }); Using(activator); var bus = CreateBus(withCompressionEnabled, activator); bus.SendLocal(new TextMessage {Text = LongText}).Wait(); gotIt.WaitOrDie(TimeSpan.FromSeconds(10)); }
static void Main() { using (var adapter = new BuiltinHandlerActivator()) { adapter.Handle<Job>(async job => { Console.WriteLine("Processing job {0}", job.JobNumber); await Task.Delay(TimeSpan.FromMilliseconds(300)); }); Configure.With(adapter) .Logging(l => l.ColoredConsole(LogLevel.Warn)) .Transport(t => t.UseSqlServer("server=.; initial catalog=rebus; integrated security=true", "Messages", "consumer")) .Options(o => { o.SetNumberOfWorkers(1); o.SetMaxParallelism(20); }) .Start(); Console.WriteLine("Consumer listening - press ENTER to quit"); Console.ReadLine(); } }
protected override void SetUp() { var inMemNetwork = new InMemNetwork(); _service = CreateEndpoint(inMemNetwork, "service"); _client = CreateEndpoint(inMemNetwork, "client"); }
public async Task CanForwardToMultipleRecipients() { var network = new InMemNetwork(); var activator = new BuiltinHandlerActivator(); Using(activator); var recipients = new[] { "recipient-A", "recipient-B" }.ToList(); recipients.ForEach(network.CreateQueue); Configure.With(activator) .Transport(t => t.UseInMemoryTransport(network, "forwarder")) .Routing(t => { t.AddTransportMessageForwarder(async transportMessage => ForwardAction.ForwardTo(recipients)); }) .Start(); await activator.Bus.SendLocal("HEJ MED DIG!!!"); var transportMessages = await Task.WhenAll(recipients.Select(async queue => { var message = await network.WaitForNextMessageFrom(queue); return message; })); Assert.That(transportMessages.Length, Is.EqualTo(2)); }
protected override void SetUp() { _inMemNetwork = new InMemNetwork(); _inMemDataStore = new InMemDataStore(); _senderBus = StartBus("sender").Bus; _receiverActivator = StartBus("receiver"); }
protected override void SetUp() { _activator = Using(new BuiltinHandlerActivator()); _bus = Configure.With(_activator) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "headers")) .Start(); }
protected override void SetUp() { StandardAzureServiceBusTransportFactory.DeleteTopic(typeof (string).GetSimpleAssemblyQualifiedName().ToValidAzureServiceBusEntityName()); _bus1 = StartBus(_inputQueueName1); _bus2 = StartBus(_inputQueueName2); _bus3 = StartBus(_inputQueueName3); }
public MessageProcessor(Func <IsolationLevel?, IUnitOfWork> getUow, BuiltinHandlerActivator activator) { _getUow = getUow; _activator = activator; }
protected override void SetUp() { _activator = new BuiltinHandlerActivator(); }
static TimeSpan RunTest(int numberOfMessages, PipelineStepProfilerStats profilerStats, PipelineInvokerMode pipelineInvokerMode) { using (var adapter = new BuiltinHandlerActivator()) { var network = new InMemNetwork(); Configure.With(adapter) .Logging(l => l.Console(LogLevel.Warn)) .Transport(t => t.UseInMemoryTransport(network, "perftest")) .Options(o => { o.SetNumberOfWorkers(0); o.SetMaxParallelism(1); o.Decorate <IPipeline>(c => new PipelineStepProfiler(c.Get <IPipeline>(), profilerStats)); switch (pipelineInvokerMode) { case PipelineInvokerMode.Default: o.Register <IPipelineInvoker>(c => new DefaultPipelineInvoker(c.Get <IPipeline>())); break; case PipelineInvokerMode.DefaultNew: o.Register <IPipelineInvoker>(c => new DefaultPipelineInvokerNew(c.Get <IPipeline>())); break; case PipelineInvokerMode.Action: o.Register <IPipelineInvoker>(c => new ActionPipelineInvoker(c.Get <IPipeline>())); break; default: throw new ArgumentOutOfRangeException($"Unknown pipeline invoker: {pipelineInvokerMode}"); } }) .Start(); var serializer = new JsonSerializer(new SimpleAssemblyQualifiedMessageTypeNameConvention()); var boy = new SomeMessage("hello there!"); for (var counter = 0; counter < numberOfMessages; counter++) { var headers = new Dictionary <string, string> { { Headers.MessageId, Guid.NewGuid().ToString() } }; var message = new Message(headers, boy); var transportMessage = serializer.Serialize(message).Result; var inMemTransportMessage = transportMessage.ToInMemTransportMessage(); network.Deliver("perftest", inMemTransportMessage); } ; var numberOfReceivedMessages = 0; var gotAllMessages = new ManualResetEvent(false); adapter.Handle <SomeMessage>(async m => { Interlocked.Increment(ref numberOfReceivedMessages); if (Volatile.Read(ref numberOfReceivedMessages) == numberOfMessages) { gotAllMessages.Set(); } }); var stopwatch = Stopwatch.StartNew(); adapter.Bus.Advanced.Workers.SetNumberOfWorkers(1); gotAllMessages.WaitOrDie(TimeSpan.FromSeconds(30)); return(stopwatch.Elapsed); } }
static void RegisterGeneric <THandler>(BuiltinHandlerActivator activator, ConstructorInfo constructor) where THandler : IHandleMessages { activator.Register(() => (THandler)constructor.Invoke(new object[0])); }
void CreateBus(string queueName, BuiltinHandlerActivator activator) { Configure.With(activator) .Transport(t => t.UseInMemoryTransport(_network, queueName)) .Start(); }
public async Task DoesntIgnoreDefinedTimeoutWhenReceiving(AzureServiceBusMode mode, int operationTimeoutInSeconds) { var operationTimeout = TimeSpan.FromSeconds(operationTimeoutInSeconds); var connString = StandardAzureServiceBusTransportFactory.ConnectionString; var builder = new ServiceBusConnectionStringBuilder(connString) { OperationTimeout = operationTimeout }; var newConnString = builder.ToString(); var consoleLoggerFactory = new ConsoleLoggerFactory(false); var transport = new AzureServiceBusTransport(newConnString, QueueName, consoleLoggerFactory, new TplAsyncTaskFactory(consoleLoggerFactory)); Using(transport); transport.PurgeInputQueue(); //Create the queue for the receiver since it cannot create it self beacuse of lacking rights on the namespace transport.CreateQueue(QueueName); var senderActivator = new BuiltinHandlerActivator(); var senderBus = Configure.With(senderActivator) .Transport(t => t.UseAzureServiceBus(newConnString, "sender", mode)) .Start(); Using(senderBus); // queue 3 messages await senderBus.Advanced.Routing.Send(QueueName, "message to receiver"); await senderBus.Advanced.Routing.Send(QueueName, "message to receiver2"); await senderBus.Advanced.Routing.Send(QueueName, "message to receiver3"); await Task.Delay(TimeSpan.FromSeconds(2)); // wait a bit to make sure the messages are queued. // receive 1 using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, _cancellationToken); sw.Stop(); await scope.CompleteAsync(); msg.Should().NotBeNull(); sw.Elapsed.Should().BeLessThan(TimeSpan.FromMilliseconds(1500)); } // receive 2 using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, _cancellationToken); sw.Stop(); await scope.CompleteAsync(); msg.Should().NotBeNull(); sw.Elapsed.Should().BeLessThan(TimeSpan.FromMilliseconds(1500)); } // receive 3 using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, _cancellationToken); sw.Stop(); await scope.CompleteAsync(); msg.Should().NotBeNull(); sw.Elapsed.Should().BeLessThan(TimeSpan.FromMilliseconds(1500)); } // receive 4 - NOTHING using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, _cancellationToken); sw.Stop(); await scope.CompleteAsync(); msg.Should().BeNull(); sw.Elapsed.Should().BeCloseTo(operationTimeout, 2000); } // put 1 more message await senderBus.Advanced.Routing.Send(QueueName, "message to receiver5"); await Task.Delay(TimeSpan.FromSeconds(2)); // wait a bit to make sure the messages are queued. // receive 5 using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, _cancellationToken); sw.Stop(); await scope.CompleteAsync(); msg.Should().NotBeNull(); sw.Elapsed.Should().BeLessThan(TimeSpan.FromMilliseconds(1500)); } // receive 6 - NOTHING using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, _cancellationToken); sw.Stop(); await scope.CompleteAsync(); msg.Should().BeNull(); sw.Elapsed.Should().BeCloseTo(operationTimeout, 2000); } }
async Task RunTest(string type, int messageCount) { var counter = new SharedCounter(messageCount); var receivedMessagePriorities = new List <int>(); var server = new BuiltinHandlerActivator(); server.Handle <string>(async str => { Console.WriteLine($"Received message: {str}"); var parts = str.Split(' '); var priority = int.Parse(parts[1]); receivedMessagePriorities.Add(priority); counter.Decrement(); }); var serverBus = Configure.With(Using(server)) .Transport(t => { if (type == "normal") { t.UseSqlServer(SqlTestHelper.ConnectionString, "server"); } else { t.UseSqlServerInLeaseMode(SqlTestHelper.ConnectionString, "server"); } }) .Options(o => { o.SetNumberOfWorkers(0); o.SetMaxParallelism(1); }) .Start(); var clientBus = Configure.With(Using(new BuiltinHandlerActivator())) .Transport(t => { if (type == "normal") { t.UseSqlServerAsOneWayClient(SqlTestHelper.ConnectionString); } else { t.UseSqlServerInLeaseModeAsOneWayClient(SqlTestHelper.ConnectionString); } }) .Routing(t => t.TypeBased().Map <string>("server")) .Start(); await Task.WhenAll(Enumerable.Range(0, messageCount) .InRandomOrder() .Select(priority => SendPriMsg(clientBus, priority))); serverBus.Advanced.Workers.SetNumberOfWorkers(1); counter.WaitForResetEvent(); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.That(receivedMessagePriorities.Count, Is.EqualTo(messageCount)); Assert.That(receivedMessagePriorities.ToArray(), Is.EqualTo(Enumerable.Range(0, messageCount).Reverse().ToArray())); }
/// <summary> /// Hack that can be used in situations where the order of starting the bus/handler registration is mixed up /// (because it was changed at some point in time to throw exceptions if handlers were registering AFTER starting the bus) /// </summary> public static BuiltinHandlerActivator AddHandlerWithBusTemporarilyStopped <TMessage>(this BuiltinHandlerActivator activator, Func <IBus, IMessageContext, TMessage, Task> handler) { WithoutAnyWorkers(activator.Bus, () => activator.Handle(handler)); return(activator); }
public async Task CanFinishSaga() { var activator = new BuiltinHandlerActivator(); var events = new ConcurrentQueue <string>(); activator.Register(() => new TestSaga(events, 3)); Using(activator); var bus = Configure.With(activator) .Logging(l => l.Console(minLevel: LogLevel.Warn)) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(true), "finish-saga-test")) .Sagas(s => s.Register(c => _factory.GetSagaStorage())) .Options(o => { o.SetNumberOfWorkers(1); o.SetMaxParallelism(1); }) .Start(); const int millisecondsDelay = 300; var stopwatch = Stopwatch.StartNew(); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); await Task.Delay(millisecondsDelay); await Task.Delay(millisecondsDelay); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); Assert.That(events.ToArray(), Is.EqualTo(new[] { "70:1", "70:2", "70:3", // it is marked as completed here "70:1", "70:2", })); }
public async Task DoesntIgnoreDefinedTimeoutWhenReceiving(int operationTimeoutInSeconds) { var operationTimeout = TimeSpan.FromSeconds(operationTimeoutInSeconds); var connString = AsbTestConfig.ConnectionString; var consoleLoggerFactory = new ConsoleLoggerFactory(false); var transport = new AzureServiceBusTransport(connString, QueueName, consoleLoggerFactory, new TplAsyncTaskFactory(consoleLoggerFactory), new DefaultNameFormatter()); transport.ReceiveOperationTimeout = TimeSpan.FromSeconds(operationTimeoutInSeconds); Using(transport); transport.Initialize(); transport.PurgeInputQueue(); //Create the queue for the receiver since it cannot create it self beacuse of lacking rights on the namespace transport.CreateQueue(QueueName); var senderActivator = new BuiltinHandlerActivator(); var senderBus = Configure.With(senderActivator) .Transport(t => t.UseAzureServiceBus(connString, "sender")) .Start(); Using(senderBus); // queue 3 messages await senderBus.Advanced.Routing.Send(QueueName, "message to receiver"); await senderBus.Advanced.Routing.Send(QueueName, "message to receiver2"); await senderBus.Advanced.Routing.Send(QueueName, "message to receiver3"); //await Task.Delay(TimeSpan.FromSeconds(2)); // wait a bit to make sure the messages are queued. // receive 1 using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, CancellationToken.None); sw.Stop(); await scope.CompleteAsync(); Assert.That(msg, Is.Not.Null); Assert.That(sw.Elapsed, Is.LessThan(TimeSpan.FromMilliseconds(1500))); } // receive 2 using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, CancellationToken.None); sw.Stop(); await scope.CompleteAsync(); Assert.That(msg, Is.Not.Null); Assert.That(sw.Elapsed, Is.LessThan(TimeSpan.FromMilliseconds(1500))); } // receive 3 using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, CancellationToken.None); sw.Stop(); await scope.CompleteAsync(); Assert.That(msg, Is.Not.Null); Assert.That(sw.Elapsed, Is.LessThan(TimeSpan.FromMilliseconds(1500))); } // receive 4 - NOTHING using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, CancellationToken.None); sw.Stop(); await scope.CompleteAsync(); Assert.That(msg, Is.Null); Assert.That(sw.Elapsed, Is.LessThan(operationTimeout.Add(TimeSpan.FromSeconds(2))).And.GreaterThan(operationTimeout.Subtract(TimeSpan.FromSeconds(2)))); } // put 1 more message await senderBus.Advanced.Routing.Send(QueueName, "message to receiver5"); await Task.Delay(TimeSpan.FromSeconds(2)); // wait a bit to make sure the messages are queued. // receive 5 using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, CancellationToken.None); sw.Stop(); await scope.CompleteAsync(); Assert.That(msg, Is.Not.Null); Assert.That(sw.Elapsed, Is.LessThan(TimeSpan.FromMilliseconds(1500))); } // receive 6 - NOTHING using (var scope = new RebusTransactionScope()) { var sw = System.Diagnostics.Stopwatch.StartNew(); var msg = await transport.Receive(scope.TransactionContext, CancellationToken.None); sw.Stop(); await scope.CompleteAsync(); Assert.That(msg, Is.Null); Assert.That(sw.Elapsed, Is.LessThan(operationTimeout.Add(TimeSpan.FromSeconds(2))).And.GreaterThan(operationTimeout.Subtract(TimeSpan.FromSeconds(2)))); } }
public async Task PublishBunchOfMessages(bool enablePublisherConfirms, int count) { var queueName = TestConfig.GetName("pub-conf"); Using(new QueueDeleter(queueName)); var activator = new BuiltinHandlerActivator(); Using(activator); activator.Handle <string>(async str => { }); Configure.With(activator) .Logging(l => l.Console(LogLevel.Info)) .Transport(t => t.UseRabbitMq(ConnectionString, queueName) .SetPublisherConfirms(enabled: enablePublisherConfirms)) .Start(); // In transaction using (var scope = new RebusTransactionScope()) { var stopwatch = Stopwatch.StartNew(); await Task.WhenAll(Enumerable.Range(0, count) .Select(n => $"THIS IS MESSAGE NUMBER {n} OUT OF {count}") .Select(str => activator.Bus.SendLocal(str))); await scope.CompleteAsync(); var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; Console.WriteLine($@"Publishing {count} messages in transaction with PUBLISHER CONFIRMS = {enablePublisherConfirms} took {elapsedSeconds:0.0} s - that's {count/elapsedSeconds:0.0} msg/s"); } // Without transaction var stopwatch2 = Stopwatch.StartNew(); await Task.WhenAll(Enumerable.Range(0, count) .Select(n => $"THIS IS MESSAGE NUMBER {n} OUT OF {count}") .Select(str => activator.Bus.SendLocal(str))); var elapsedSeconds2 = stopwatch2.Elapsed.TotalSeconds; Console.WriteLine($@"Publishing {count} messages without transaction with PUBLISHER CONFIRMS = {enablePublisherConfirms} took {elapsedSeconds2:0.0} s - that's {count/elapsedSeconds2:0.0} msg/s"); }
public AbpRebusRabbitMqConsumerModule() { _activator = new BuiltinHandlerActivator(); }
protected override void SetUp() { _publisher = GetBus(_publisherQueueName); }
public async Task ItWorks() { // now that the container is not automatically created, we need to do this await _container.CreateIfNotExistsAsync(); var sasWithReadAccess = GetSas(SharedAccessAccountPermissions.Read); var sasWithWriteAccess = GetSas(SharedAccessAccountPermissions.Write); var receivedMessages = new ConcurrentQueue <string>(); var network = new InMemNetwork(); // this is the receiver using var receiver = new BuiltinHandlerActivator(); receiver.Handle <DataBusAttachment>(async attachment => { using var source = await attachment.OpenRead(); using var reader = new StreamReader(source); receivedMessages.Enqueue(await reader.ReadToEndAsync()); }); Configure.With(receiver) .Transport(t => t.UseInMemoryTransport(network, "receiver")) .DataBus(d => d.StoreInBlobStorage(new Uri(sasWithReadAccess)).DoNotUpdateLastReadTime()) .Start(); // create a sender using var sender = new BuiltinHandlerActivator(); Configure.With(sender) .Transport(t => t.UseInMemoryTransport(network, "sender")) .DataBus(d => d.StoreInBlobStorage(new Uri(sasWithWriteAccess)).DoNotCreateContainer()) .Routing(t => t.TypeBased().Map <DataBusAttachment>("receiver")) .Start(); // send attachment const string expectedText = "hey ven! 🍺"; using var bytes = new MemoryStream(Encoding.UTF8.GetBytes(expectedText)); var attachment = await sender.Bus.Advanced.DataBus.CreateAttachment(bytes); await sender.Bus.Send(attachment); await receivedMessages.WaitUntil(q => q.Count == 1, timeoutSeconds : 5); // return; // Console.WriteLine($@"Normal connection string: // {AzureConfig.ConnectionString} //Container URI: // {_container.Uri} //SAS token: // {readSasToken} //Combined: // {sasWithReadAccess} //"); // var blobs = readContainer.ListBlobs().ToList(); // Console.WriteLine($@"Found these blobs: //{string.Join(Environment.NewLine, blobs.Select(b => $" {b.Uri}"))} //og det er fint"); }
public Client(RabbitMqBusConfiguration configuration) { Configuration = configuration; _activator = new BuiltinHandlerActivator(); }
static void Main() { const string QUEUE = "rebus-Publisher"; const string QUEUE_ERRORS = "rebus-errors"; const string QUEUE_GEOCODER = "rebus-ReverseGeocoder"; using (var activator = new BuiltinHandlerActivator()) { activator.Register((bus, messageContext) => new Handler(bus, messageContext)); /* * // for local Debug... * Configure.With(activator) * .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn)) * .Options(o => o.SimpleRetryStrategy(errorQueueAddress: QUEUE_ERRORS)) * .Transport(t => t.UseFileSystem(@"c:\servicebus\", QUEUE)) * .Subscriptions(s => s.UseJsonFile(@"c:\servicebus\subscriptions.json")) * .Routing(r => r.TypeBased().MapAssemblyOf<ReverseGeoRequest>(QUEUE_GEOCODER)) * .Start(); /**/ /* * // for integration-tests * Configure.With(activator) * .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn)) * .Options(o => o.SimpleRetryStrategy(errorQueueAddress: QUEUE_ERRORS)) * .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), QUEUE)) * .Subscriptions(s => s.StoreInMemory(new InMemorySubscriberStore())) // useful in Unit-tests * .Routing(r => r.TypeBased().MapAssemblyOf<ReverseGeoRequest>(QUEUE_GEOCODER)) * .Start(); /**/ // Azure Service Bus... const string CONNECTION_STRING = ""; Configure.With(activator) .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn)) .Options(o => o.SimpleRetryStrategy(errorQueueAddress: QUEUE_ERRORS)) .Transport(t => t.UseAzureServiceBus(CONNECTION_STRING, QUEUE)) .Routing(r => r.TypeBased().MapAssemblyOf <ReverseGeoRequest>(QUEUE_GEOCODER)) .Start(); /**/ var startupTime = DateTime.Now; while (true) { Console.WriteLine(@"1) Publish String Notification"); Console.WriteLine(@"2) Publish DateTime Notification"); Console.WriteLine(@"3) Publish TimeSpan Notification"); Console.WriteLine(@"4) Send ReverseGeoCode Request"); Console.WriteLine(@"q) Quit"); var keyChar = char.ToLower(Console.ReadKey(true).KeyChar); var busSync = activator.Bus.Advanced.SyncBus; switch (keyChar) { case '1': busSync.Publish(new StringNotification("Hello there, this is a string notification from a Publisher!")); break; case '2': busSync.Publish(new DateTimeNotification(DateTime.Now)); break; case '3': busSync.Publish(new TimeSpanNotification(DateTime.Now - startupTime)); break; case '4': busSync.Send(new ReverseGeoRequest(10, 20)); break; case 'q': Console.WriteLine("Quitting!"); return; } } } }
public void InitConfig(BuiltinHandlerActivator activator) { Configure.With(activator) .Transport(t => t.UseRabbitMq("amqp://192.168.99.100", Assembly.GetEntryAssembly().GetName().Name)) .Start(); }
public void WorksWithPrefetch(int prefetch, int numberOfMessages) { AdjustLogging(LogLevel.Info); var activator = new BuiltinHandlerActivator(); var receivedMessages = 0; var done = new ManualResetEvent(false); activator.Handle <string>(async str => { Interlocked.Increment(ref receivedMessages); if (receivedMessages == numberOfMessages) { done.Set(); } }); Console.WriteLine("Sending {0} messages", numberOfMessages); using (var transport = GetTransport()) { var tasks = Enumerable.Range(0, numberOfMessages) .Select(i => string.Format("THIS IS MESSAGE # {0}", i)) .Select(async msg => { using (var context = new DefaultTransactionContext()) { var headers = DefaultHeaders(); var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(msg)); var transportMessage = new TransportMessage(headers, body); await transport.Send(QueueName, transportMessage, context); await context.Complete(); } }) .ToArray(); Task.WhenAll(tasks).Wait(); } Console.WriteLine("Receiving {0} messages", numberOfMessages); var stopwatch = Stopwatch.StartNew(); using (Configure.With(activator) .Transport(t => { t.UseAzureServiceBus(AzureServiceBusTransportFactory.ConnectionString, QueueName) .EnablePrefetching(prefetch); }) .Options(o => { o.SetNumberOfWorkers(5); o.SetMaxParallelism(10); }) .Start()) { done.WaitOrDie(TimeSpan.FromSeconds(numberOfMessages * 0.1 + 3)); } var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; Console.WriteLine("Receiving {0} messages took {1:0.0} s - that's {2:0.0} msg/s", numberOfMessages, elapsedSeconds, numberOfMessages / elapsedSeconds); }
static async Task Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.RollingFile("log-.txt") .CreateLogger(); var queueName = $"{Environment.MachineName}_{Process.GetCurrentProcess().Id}".ToLowerInvariant(); var workHandlerActivator = new BuiltinHandlerActivator(); var clientActivator = new BuiltinHandlerActivator(); using (var builtinHandlerActivator = new DisposeChain(clientActivator, workHandlerActivator)) { // Setup worker bus workHandlerActivator.Handle <Rebus.AwsSnsAndSqs.RebusAmazon.VinEventMessage>(message => { // igonore message we sent if (message.Source == queueName) { return(Task.CompletedTask); } Console.WriteLine(); Console.WriteLine($"{message.TimeStamp:g}: {message.Message}"); Console.Write("message:"); return(Task.CompletedTask); }); var worker = Configure .With(workHandlerActivator) .Logging(configurer => configurer.Serilog(Log.Logger)) .Transport(t => { // set the worker queue name t.UseAmazonSnsAndSqs(workerQueueAddress: queueName); }) .Routing(r => { // Map the message type to the queue r.TypeBased().Map <MessengerMessage>(queueName); }) .Start(); // add the current queue to the MessengerMessage topic await worker.Subscribe <MessengerMessage>(); // setup a client var client = Configure .With(clientActivator) .Logging(configurer => configurer.Serilog(Log.Logger)) .Transport(t => t.UseAmazonSnsAndSqsAsOneWayClient()) .Start(); var line = String.Empty; do { Console.Write("message:"); line = Console.ReadLine(); // publish a message to the MessengerMessage topic await client.PublishEvent(new VinEventMessage { Message = line, EventId = Guid.NewGuid(), MessageVersion = new Version(1, 0), Source = "RebusSnsSqsExample.Application", MessageType = "Test.Test", }); }while (string.IsNullOrWhiteSpace(line) == false); // remove the worker queue from the topic await worker.Unsubscribe <MessengerMessage>(); } }
public SendTransactionalEmail(BuiltinHandlerActivator adapter) { InitializeComponent(); this.Adapter = adapter; }
public async Task CanFinishSaga() { var activator = new BuiltinHandlerActivator(); var events = new ConcurrentQueue <string>(); activator.Register(() => new TestSaga(events, 3)); Using(activator); var bus = Configure.With(activator) .Logging(l => l.Console(minLevel: LogLevel.Warn)) .Transport(t => t.UseInMemoryTransport(new InMemNetwork(true), "finish-saga-test")) .Sagas(s => s.Register(c => _factory.GetSagaStorage())) .Options(o => { o.SetNumberOfWorkers(1); o.SetMaxParallelism(1); }) .Start(); const int millisecondsDelay = 500; var stopwatch = Stopwatch.StartNew(); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); await bus.SendLocal(new SagaMessage { Id = 70 }); await Task.Delay(millisecondsDelay); await Task.Delay(3 *millisecondsDelay); var expected = new[] { "70:1", "70:2", "70:3", // it is marked as completed here "70:1", "70:2", }; var actual = events.ToArray(); Console.WriteLine($"t: {stopwatch.Elapsed.TotalMilliseconds:0.#} ms"); Assert.That(actual, Is.EqualTo(expected), $@"Received events {string.Join(Environment.NewLine, actual)} did not match expected {string.Join(Environment.NewLine, expected)} Five events with ID = 70 are sent. The saga stamps 'events' down along with the number of messages it has processed - e.g. 70:2 means 'Message with ID 70 handled as the 2nd message'. The saga was supposed to receive the first three events and then mark itself as completed. After that, the last two events should have been received. "); }
/// <summary> /// Sets up the EventClient to download events from the ServiceBus and files from the Signere API. Note that the primary key gives elevated privileges and is not necessary for subscribing to events - using secondary key is normally sufficient (see SetupWithSecondaryKey). /// </summary> /// <param name="azureServiceBusConnectionString">Your ServiceBus connection string. Contact [email protected] to get this</param> /// <param name="DocumentProvider">Your account ID</param> /// <param name="ApiKey">Your primary API key</param> /// <returns>EventClient set up using the primary API key</returns> public static EventClient SetupWithPrimaryApiKey(string azureServiceBusConnectionString, Guid DocumentProvider, string ApiKey) { var adapter = new BuiltinHandlerActivator(); return(new EventClient(adapter, azureServiceBusConnectionString, DocumentProvider, ApiKey, false)); }
public MyMessageSubscriber() { _activator = new BuiltinHandlerActivator(); }
public async Task NizzleName(int numberOfMessages, int numberOfWorkers) { var activator = new BuiltinHandlerActivator(); var sentMessageIds = new ConcurrentDictionary <int, int>(); var receivedMessageIds = new ConcurrentDictionary <int, int>(); activator.Handle <SomeMessage>(async message => { var id = message.Id; receivedMessageIds.AddOrUpdate(id, i => 1, (i, existing) => existing + 1); }); var bus = (RebusBus)Configure.With(activator) .Logging(l => l.None()) .Transport(t => t.UseMsmq(InputQueueName)) .Routing(t => t.TypeBased().Map <SomeMessage>(InputQueueName)) .Options(o => o.SetNumberOfWorkers(0)) .Start(); Using(bus); var sendStopwatch = Stopwatch.StartNew(); Console.WriteLine("Sending {0} messages", numberOfMessages); await Task.WhenAll(Enumerable .Range(0, numberOfMessages) .Select(async id => { await bus.Send(new SomeMessage { Id = id }); sentMessageIds[id] = 1; })); var elapsedSending = sendStopwatch.Elapsed; Console.WriteLine("SENT {0} messages in {1:0.0} s - that's {2:0.0}/s", numberOfMessages, elapsedSending.TotalSeconds, numberOfMessages / elapsedSending.TotalSeconds); bus.SetNumberOfWorkers(numberOfWorkers); var receiveStopwatch = Stopwatch.StartNew(); Console.WriteLine("Waiting until they have been received"); while (receivedMessageIds.Count < numberOfMessages) { Console.WriteLine("got {0} messages so far...", receivedMessageIds.Count); await Task.Delay(1000); } var elapsedReceiving = receiveStopwatch.Elapsed; Console.WriteLine("RECEIVED {0} messages in {1:0.0} s - that's {2:0.0}/s", numberOfMessages, elapsedReceiving.TotalSeconds, numberOfMessages / elapsedReceiving.TotalSeconds); var sentButNotReceived = sentMessageIds.Keys.Except(receivedMessageIds.Keys).ToList(); var receivedMoreThanOnce = receivedMessageIds.Where(kvp => kvp.Value > 1).ToList(); if (sentButNotReceived.Any()) { Assert.Fail("The following IDs were sent but not received: {0}", string.Join(", ", sentButNotReceived)); } if (receivedMoreThanOnce.Any()) { Assert.Fail("The following IDs were received more than once: {0}", string.Join(", ", receivedMoreThanOnce.Select(kvp => $"{kvp.Key} ({kvp.Value})"))); } }
public MessageBotService(ILogger <MessageBotService> logger, IConfiguration configuration) { _logger = logger; _configuration = configuration; _activator = new BuiltinHandlerActivator(); }