public EventBus(IBusContext context, ITextSerializer serializer) { if (context == null) throw new ArgumentNullException(nameof(context)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); _context = context; _serializer = serializer; }
public Closed( BusConfiguration configuration, IConnectionManager connectionManager, IBusContext context) : base(configuration, connectionManager, context) { base.Logger.Info("ctor Completed"); }
public static void TryEnqueue(this IBusContext ctx, CacheMessage message) { if (message == null) { return; } ctx.Enqueue(ContextName, message); }
public EventReplayService(IBusContext <IConnection> context, IServiceCollection services, int timeout) { _queues = new Stack <string>(); _services = services; _context = context; _timeout = timeout; _channel = _context.Connection.CreateModel(); }
public Task Start(IBusContext context) { ErrorsNotifications errors = busNotifications.Errors; errors.MessageHasBeenSentToSecondLevelRetries += (sender, retry) => LogToConsole(retry); errors.MessageHasFailedAFirstLevelRetryAttempt += (sender, retry) => LogToConsole(retry); errors.MessageSentToErrorQueue += (sender, retry) => LogToConsole(retry); return(Task.FromResult(0)); }
public async Task InterfaceMessage() { IBusContext busContext = null; #region InterfacePublish await busContext.Publish <IMyEvent>(m => { m.SomeProperty = "Hello world"; }); #endregion }
// Shut down server before sending this message, after 30 seconds, the message will be moved to Transactional dead-letter messages queue. static async Task Expiration(IBusContext bus) { await bus.Send(new MessageThatExpires { RequestId = new Guid() }); Console.WriteLine("message with expiration was sent"); }
/// <summary> /// Initializes a new instance of the <see cref="RabbitChannel"/> class. /// </summary> /// <param name="connectionId">A connection identifier to which this channel belongs</param> /// <param name="model">A native transport channel</param> /// <param name="busContext">A bus context</param> public RabbitChannel(Guid connectionId, IModel model, IBusContext busContext) { this.ConnectionId = connectionId; this.Model = model; this.busContext = busContext; this.logger = LogManager.GetLogger($"{this.GetType().FullName}({this.ConnectionId}, {this.GetHashCode()})"); this.Model.ModelShutdown += this.OnModelShutdown; }
public static void Send <T>(this IBusContext ctx, T message, bool onCallback = false, string contextName = null) where T : class, ISpecializedMessage { if (message == null) { return; } SendInternal(ctx, message, onCallback, contextName); }
private static void SendInternal(this IBusContext ctx, CacheMessage message, bool onCallback = false) { if (onCallback) { message.Token = message.Token ?? message.RequestId.ToString(); MessageLogger.Sended(message); } ctx.Enqueue(ContextName, message); }
/// <summary> /// Initialize a message receiver with a context, queue name and topic filters /// </summary> public RabbitMqMessageReceiver(IBusContext <IConnection> context, string queueName, IEnumerable <string> topicFilters) { Context = context; Model = Context.Connection.CreateModel(); QueueName = queueName; TopicFilters = topicFilters; Consumer = new EventingBasicConsumer(Model); Logger = RabbitMqLoggerFactory.CreateInstance <RabbitMqMessageReceiver>(); ConsumerTag = Guid.NewGuid().ToString(); }
static async Task SendJsonMessage(IBusContext busContext) { MessageWithJson message = new MessageWithJson { SomeProperty = "Some content in a json message", }; await busContext.Send("Samples.MultiSerializer.Receiver", message); Console.WriteLine("Json Message sent"); }
static async Task SendRequest(IBusContext bus) { Guid requestId = Guid.NewGuid(); await bus.Send(new Request { RequestId = requestId }); Console.WriteLine("Request sent id: " + requestId); }
static async Task PublishEvent(IBusContext busContext) { Guid eventId = Guid.NewGuid(); await busContext.Publish <IMyEvent>(m => { m.EventId = eventId; }); Console.WriteLine("Event published, id: " + eventId); }
public async Task RequestImmediateDispatchUsingScope() { IBusContext busContext = null; #region RequestImmediateDispatchUsingScope using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { await busContext.SendLocal(new MyMessage()); } #endregion }
public BestelStatusController( IBusContext <IConnection> context, IBestellingDataMapper bestellingDataMapper, IEventPublisher eventPublisher, ILoggerFactory loggerFactory) { _bestellingDataMapper = bestellingDataMapper; _eventPublish = eventPublisher; _commandSender = context.CreateCommandSender(); _logger = loggerFactory.CreateLogger <BestelStatusController>(); }
public async Task RequestImmediateDispatch() { IBusContext busContext = null; #region RequestImmediateDispatch var options = new SendOptions(); options.RequireImmediateDispatch(); await busContext.Send(new MyMessage(), options); #endregion }
public async Task Subscribe() { IBusContext busContext = null; #region ExplicitSubscribe await busContext.Subscribe <MyEvent>(); await busContext.Unsubscribe <MyEvent>(); #endregion }
static async Task AsyncMain() { #region config BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.Serialization.Xml"); // this is optional since Xml is the default serializer busConfiguration.UseSerialization <XmlSerializer>(); // register the mutator so the the message on the wire is written busConfiguration.RegisterComponents(components => { components.ConfigureComponent <MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion busConfiguration.UsePersistence <InMemoryPersistence>(); busConfiguration.EnableInstallers(); busConfiguration.SendFailedMessagesTo("error"); IEndpointInstance endpoint = await Endpoint.Start(busConfiguration); try { IBusContext busContext = endpoint.CreateBusContext(); #region message CreateOrder message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List <OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; await busContext.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpoint.Stop(); } }
static async Task SendMessageTooLargePayload(IBusContext bus) { #region SendMessageTooLargePayload AnotherMessageWithLargePayload message = new AnotherMessageWithLargePayload { LargeBlob = new byte[1024 * 1024 * 5] //5MB }; await bus.Send("Samples.DataBus.Receiver", message); #endregion }
async Task DisablePerMessage() { IBusContext busContext = null; #region DisableBestPracticeEnforcementPerMessage SendOptions options = new SendOptions(); options.DoNotEnforceBestPractices(); await busContext.Send(new MyEvent(), options); #endregion }
/// <summary> /// Initializes a new instance of the <see cref="RabbitDelivery"/> class. /// </summary> /// <param name="busContext"> /// The bus Context. /// </param> /// <param name="channel"> /// Канал поставки сообщения. /// </param> /// <param name="args"> /// Параметры поставки сообщения. /// </param> /// <param name="requiresAccept"> /// Верно, если требуется подтверждение доставки. /// </param> public RabbitDelivery(IBusContext busContext, RabbitChannel channel, BasicDeliverEventArgs args, bool requiresAccept) { this.busContext = busContext; this.Channel = channel; this.Label = this.busContext.MessageLabelHandler.Resolve(args); this.Args = args; this.requiresAccept = requiresAccept; this.headers = new Lazy <IDictionary <string, object> >( () => this.ExtractHeadersFrom(args)); }
static async Task SendCommand(IBusContext bus) { Guid commandId = Guid.NewGuid(); await bus.Send(new MyCommand { CommandId = commandId, EncryptedString = "Some sensitive information" }); Console.WriteLine("Command sent id: " + commandId); }
public async Task ConcreteMessage() { IBusContext busContext = null; #region InstancePublish MyEvent message = new MyEvent { SomeProperty = "Hello world" }; await busContext.Publish(message); #endregion }
static void Start(IBusContext busContext) { Console.WriteLine("Press '1' to publish IEvent"); Console.WriteLine("Press '2' to publish EventMessage"); Console.WriteLine("Press '3' to publish AnotherEventMessage"); Console.WriteLine("Press 'Enter' to publish a message.To exit, Ctrl + C"); #region PublishLoop while (true) { ConsoleKeyInfo key = Console.ReadKey(); Console.WriteLine(); Guid eventId = Guid.NewGuid(); switch (key.Key) { case ConsoleKey.D1: busContext.Publish <IMyEvent>(m => { m.EventId = eventId; m.Time = DateTime.Now.Second > 30 ? (DateTime?)DateTime.Now : null; m.Duration = TimeSpan.FromSeconds(99999D); }); Console.WriteLine("Published IMyEvent with Id {0}.", eventId); continue; case ConsoleKey.D2: EventMessage eventMessage = new EventMessage { EventId = eventId, Time = DateTime.Now.Second > 30 ? (DateTime?)DateTime.Now : null, Duration = TimeSpan.FromSeconds(99999D) }; busContext.Publish(eventMessage); Console.WriteLine("Published EventMessage with Id {0}.", eventId); continue; case ConsoleKey.D3: AnotherEventMessage anotherEventMessage = new AnotherEventMessage { EventId = eventId, Time = DateTime.Now.Second > 30 ? (DateTime?)DateTime.Now : null, Duration = TimeSpan.FromSeconds(99999D) }; busContext.Publish(anotherEventMessage); Console.WriteLine("Published AnotherEventMessage with Id {0}.", eventId); continue; default: return; } } #endregion }
public static void AddRabbitMQBusContext(this IServiceCollection services, Action <RabbitMQBusContextBuilder> busContextConfiguration) { services.AddTransient <IEventPublisher, EventPublisher <IConnection> >(); var builder = new RabbitMQBusContextBuilder(); busContextConfiguration(builder); IBusContext <IConnection> context = builder.CreateContext(); services.AddSingleton(context); }
public Disconnected( BusConfiguration configuration, IConnectionManager connectionManager, IBusContext context) : base(configuration, connectionManager, context) { base.Logger.Info("ctor Starting"); new Task(this.TryRestablishingConnection).Start(); base.Logger.Info("ctor Completed"); }
static async Task Data(IBusContext bus) { Guid requestId = Guid.NewGuid(); await bus.Send(new LargeMessage { RequestId = requestId, LargeDataBus = new byte[1024 * 1024 * 5] }); Console.WriteLine("Request sent id: " + requestId); }
public EventBus(IBusContext context, ITextSerializer serializer) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } _context = context; _serializer = serializer; }
protected override Task OnStop(IBusContext context) { using (var waitHandle = new ManualResetEvent(false)) { sweepTimer.Dispose(waitHandle); // TODO: Use async synchronization primitive waitHandle.WaitOne(); } subscription.Unsubscribe(); return(Task.FromResult(0)); }
private static void SendInternal <T>(this IBusContext ctx, T message, bool onCallback = false, string contextName = null) where T : class, ISpecializedMessage { contextName = contextName ?? message.ContextName; if (onCallback) { message.Token = message.Token ?? message.RequestId.ToString(); MessageLogger.Sended(message); } ctx.Enqueue(contextName, message); }
public async Task Start(Guid taskId, IBusContext busContext) { TaskDefinition taskDefinition; if (!scheduledTasks.TryGetValue(taskId, out taskDefinition)) { logger.InfoFormat("Could not find any scheduled task with id {0}. The DefaultScheduler does not persist tasks between restarts.", taskId); return; } await DeferTask(taskDefinition, busContext).ConfigureAwait(false); await ExecuteTask(taskDefinition, busContext).ConfigureAwait(false); }
protected override Task OnStop(IBusContext context) { using (var waitHandle = new ManualResetEvent(false)) { timer.Dispose(waitHandle); // TODO: Use async synchronization primitive waitHandle.WaitOne(); } publication.Active = false; return Publish(); }
protected override Task OnStart(IBusContext context) { publication = new HandledMessageDeclaration { EndpointName = settings.EndpointName().ToString(), UserDiscriminator = settings.EndpointInstanceName().UserDiscriminator, TransportDiscriminator = settings.EndpointInstanceName().TransportDiscriminator, HandledMessageTypes = hanledMessageTypes.Select(m => m.AssemblyQualifiedName).ToArray(), Active = true, }; timer = new Timer(state => { Publish().ConfigureAwait(false).GetAwaiter().GetResult(); }, null, heartbeatPeriod, heartbeatPeriod); return Publish(); }
Task SomeCustomMethod(IBusContext busContext) { return Task.FromResult(0); }
protected override async Task OnStart(IBusContext context) { var routingTable = settings.Get<UnicastRoutingTable>(); var endpointInstances = settings.Get<EndpointInstances>(); routingTable.AddDynamic((list, bag) => FindDestination(list)); endpointInstances.AddDynamic(FindInstances); subscription = await dataBackplane.GetAllAndSubscribeToChanges("NServiceBus.HandledMessages", async e => { var deserializedData = JsonConvert.DeserializeObject<HandledMessageDeclaration>(e.Data); var endpointName = new EndpointName(deserializedData.EndpointName); var instanceName = new EndpointInstanceName(endpointName, deserializedData.UserDiscriminator, deserializedData.TransportDiscriminator); var types = deserializedData.HandledMessageTypes.Select(x => Type.GetType(x, false)) .Where(x => x != null) .ToArray(); EndpointInstanceInfo instanceInfo; if (!instanceInformation.TryGetValue(instanceName, out instanceInfo)) { var newInstanceInformation = new Dictionary<EndpointInstanceName, EndpointInstanceInfo>(instanceInformation); instanceInfo = new EndpointInstanceInfo(); newInstanceInformation[instanceName] = instanceInfo; instanceInformation = newInstanceInformation; } if (deserializedData.Active) { instanceInfo.Activate(deserializedData.Timestamp); Logger.InfoFormat("Instance {0} active (heartbeat).", instanceName); } else { instanceInfo.Deactivate(); Logger.InfoFormat("Instance {0} deactivated.", instanceName); } await UpdateCaches(endpointName, instanceName, types); }, async e => { var deserializedData = JsonConvert.DeserializeObject<HandledMessageDeclaration>(e.Data); var endpointName = new EndpointName(deserializedData.EndpointName); var instanceName = new EndpointInstanceName(endpointName, deserializedData.UserDiscriminator, deserializedData.TransportDiscriminator); Logger.InfoFormat("Instance {0} removed from routing tables.", instanceName); await UpdateCaches(endpointName, instanceName, new Type[0]); instanceInformation.Remove(instanceName); }); sweepTimer = new Timer(state => { foreach (var info in instanceInformation) { if (!info.Value.Sweep(DateTime.UtcNow, heartbeatTimeout)) { Logger.InfoFormat("Instance {0} deactivated (heartbeat timeout).", info.Key); } } }, null, sweepPeriod, sweepPeriod); }
protected override Task OnStop(IBusContext context) { using (var waitHandle = new ManualResetEvent(false)) { sweepTimer.Dispose(waitHandle); // TODO: Use async synchronization primitive waitHandle.WaitOne(); } subscription.Unsubscribe(); return Task.FromResult(0); }
protected override Task OnStop(IBusContext context) { return client.Stop(); }