public ServiceBusMessageStateHandler(IReceiverClient client, Message sbMessage, IMessageSerializer serializer, int deadLetterDeliveryLimit) { DeadLetterDeliveryLimit = deadLetterDeliveryLimit; _client = client; _sbMessage = sbMessage; _message = serializer.Deserialize <T>(Encoding.UTF8.GetString(_sbMessage.Body)); }
void AddReceiveContextPayloads(ReceiveContext receiveContext, IReceiverClient receiverClient, Message message) { MessageLockContext lockContext = new ReceiverClientMessageLockContext(receiverClient, message); receiveContext.GetOrAddPayload(() => lockContext); receiveContext.GetOrAddPayload(() => _context); }
/// <summary> /// Receives from queue. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="targetModel">The target model.</param> /// <param name="handler">The handler.</param> /// <returns></returns> public bool ReceiveFromQueue <T>(T targetModel, Func <T, Task> handler) { try { ServiceBusDetails serviceBusDetails = GetServiceBusDetailsFromT(targetModel.GetType()); if (!string.IsNullOrEmpty(serviceBusDetails.Connection)) { receiverClient = new AzureQueueReceiver(serviceBusDetails.Connection, serviceBusDetails.QueueName); MessageHandlerOptions messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 50, AutoComplete = true }; //subscriptionClient.RegisterMessageHandler(handler, messageHandlerOptions); receiverClient.RegisterMessageHandler(async(msg, token) => { // Get message string message = Encoding.UTF8.GetString(msg.Body).ToBase64Decode(); dynamic obj = JsonConvert.DeserializeObject(message); dynamic retrunModel = JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(obj.originalvalue)); handler(retrunModel); }, messageHandlerOptions); return(true); } return(false); } catch (Exception) { return(false); } }
internal MessageDispatcher(IServiceScopeFactory scopeFactory, IReceiverClient client, MessageHandlerRegistry registry, LogCorrelationHandler logCorrelationHandler) { LogCorrelationHandler = logCorrelationHandler; ScopeFactory = scopeFactory; Client = client; Registry = registry; }
public async Task Start() { var serviceBusConnectionString = _configuration.GetConnectionString("AzureServiceBus"); _serviceBusConfig = _configuration.GetSection(nameof(ServiceBusConfig)).Get <ServiceBusConfig>(); var busConfig = _configuration.GetSection(nameof(BusConfig)).Get <BusConfig>(); if (busConfig != null) { _logger.LogWarning($"{busConfig.BusType} with ConnectionString {serviceBusConnectionString.ReplaceWithStars(20)} will delay start for {busConfig.BusDelayStartInSec} "); await Task.Delay(busConfig.BusDelayStartInSec * 1000); _logger.LogWarning($"{busConfig.BusType} connecting..."); } _approvedAdoProjcetMessageReceiverClient = new SubscriptionClient(serviceBusConnectionString, _serviceBusConfig.ApprovedAdoProjectsTopic, _serviceBusConfig.ApprovedAdoProjectsSub); _rejectedAdoProjcetMessageReceiverClient = new SubscriptionClient(serviceBusConnectionString, _serviceBusConfig.RejectedAdoProjectsTopic, _serviceBusConfig.RejectedAdoProjectsSub); //queueReceiverClient = new QueueClient(serviceBusConnectionString, _serviceBusConfig.QueueNameTest); var messageHandlerOptions = new MessageHandlerOptions(OnServiceBusException) { MaxConcurrentCalls = 5, AutoComplete = false }; _approvedAdoProjcetMessageReceiverClient?.RegisterMessageHandler(OnApprovedReceived, messageHandlerOptions); _rejectedAdoProjcetMessageReceiverClient?.RegisterMessageHandler(OnRejectedReceived, messageHandlerOptions); //queueReceiverClient?.RegisterMessageHandler(ExecuteQueueMessageProcessing, messageHandlerOptions); }
public Task SubscribeAsync(CancellationToken cancelToken) { if (cancelToken == null) { throw new ArgumentNullException(nameof(cancelToken)); } if (IsClosed) { throw new InvalidOperationException("Service bus connection has already been closed."); } if ((receiverClient == null) && (cancelToken.IsCancellationRequested == false)) { receiverClient = CreateReceiverClient(); var messageHandlerOptions = new MessageHandlerOptions(HandleMessagingExceptionAsync) { AutoComplete = false }; cancelToken.Register(async() => await receiverClient.CloseAsync().ConfigureAwait(false)); receiverClient.RegisterMessageHandler(HandleMessageAsync, messageHandlerOptions); } return(Task.CompletedTask); }
private void InitializeClients(ChannelType channelType) { var channelName = _configuration.GetServiceBusChannelName(channelType, _channel); var retryPolicy = new RetryExponential(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30), 10); var connectionString = _configuration.GetServiceBusConnectionString(); switch (channelType) { case ChannelType.PublishSubscribe: _receiverClient = new SubscriptionClient(connectionString, channelName, _subscriptionName, retryPolicy: retryPolicy); _senderClient = new TopicClient(connectionString, channelName, retryPolicy); break; case ChannelType.PointToPoint: var queueClient = new QueueClient(connectionString, channelName, ReceiveMode.PeekLock, retryPolicy); _receiverClient = queueClient; _senderClient = queueClient; break; default: throw new Exception($"Unkown channel type {channelType}"); } string deadPath = EntityNameHelper.FormatDeadLetterPath(_receiverClient.Path); _deadLetterQueue = new MessageReceiver(connectionString, deadPath, ReceiveMode.PeekLock); }
public ChannelReceiver(IReceiverClient receiverClient, Func <TMessage, Task> messageHandler, ILogger logger) { receiverClient.RegisterMessageHandler(async(v, token) => { try { var messageObject = JsonConvert.DeserializeObject <TMessage>(Encoding.UTF8.GetString(v.Body)); await messageHandler(messageObject).ConfigureAwait(false); } catch (Exception ex) { logger.Exception(ex); } }, new MessageHandlerOptions(v => { logger.Exception(v.Exception); return(Task.CompletedTask); }) { AutoComplete = true, MaxConcurrentCalls = 1 }); }
private async Task HandleReceivedMessage(IReceiverClient receiverClient, ISenderClient senderClient, Message message, CancellationToken token) { var eventName = message.Label; var messageData = Encoding.UTF8.GetString(message.Body); await ProcessEvent(eventName, messageData); // Complete the message so that it is not received again. await receiverClient.CompleteAsync(message.SystemProperties.LockToken); var eventType = _subscriptionsManager.GetEventTypeByName(eventName); if (eventType != null && eventType != typeof(CompletedEvent)) { var eventData = JObject.Parse(messageData); if (Guid.TryParse((string)eventData["Id"], out var eventId)) { var publisherId = (string)eventData["PublisherId"]; var completedEvent = new CompletedEvent(eventId, publisherId); await PublishEventAsync(completedEvent, senderClient); } } }
public AzureServiceBusReceiver(IReceiverClient receiverClient, ISBMessageReceiver messageReceiver, MessageHandlerOptions messageHandlerOptions) { _receiverClient = receiverClient ?? throw new ArgumentNullException(nameof(receiverClient)); _messageReceiver = messageReceiver ?? throw new ArgumentNullException(nameof(messageReceiver)); _messageHandlerOptions = messageHandlerOptions ?? new MessageHandlerOptions(DefaultExceptionReceiverHandler) { AutoComplete = false, /* * In fact, what the property actually means is the maximum about of time they lock renewal will happen for internally on the subscription client. * So if you set this to 24 hours e.g. Timespan.FromHours(24) and your processing was to take 12 hours, it would be renewed. However, if you set * this to 12 hours using Timespan.FromHours(12) and your code ran for 24, when you went to complete the message it would give a lockLost exception * (as I was getting above over shorter intervals!). * * in fact, Microsoft's implementation runs a background task that periodically renews the message lock until it expires. */ MaxAutoRenewDuration = TimeSpan.FromMinutes(10), //should be in fact called "max processing time" MaxConcurrentCalls = 2 }; _autoComplete = _messageHandlerOptions.AutoComplete; //note: we can't use management SDK as it requires high priviledged SP in Azure }
public QueueWorker( IReceiverClient messageReceiver, IWorkflowDispatcher workflowDispatcher, IOptions <AzureServiceBusOptions> options, Func <IReceiverClient, Task> disposeReceiverAction, ILogger <QueueWorker> logger) : base(messageReceiver, workflowDispatcher, options, disposeReceiverAction, logger) { }
public static Task AbandonByErrorAsync(this Message message, IReceiverClient client, Exception e) { return(client.AbandonAsync(message.SystemProperties.LockToken, new Dictionary <string, object> { { "ErrorMessage", e.Message }, { "Exception", e.ToString() } })); }
public QueueWorker( IReceiverClient messageReceiver, Scoped <IWorkflowLaunchpad> workflowLaunchpad, IOptions <AzureServiceBusOptions> options, Func <IReceiverClient, Task> disposeReceiverAction, ILogger <QueueWorker> logger) : base(messageReceiver, workflowLaunchpad, options, disposeReceiverAction, logger) { }
public TopicWorker( IReceiverClient receiverClient, Scoped <IWorkflowLaunchpad> workflowLaunchpad, IOptions <AzureServiceBusOptions> options, Func <IReceiverClient, Task> disposeReceiverAction, ILogger <TopicWorker> logger) : base(receiverClient, workflowLaunchpad, options, disposeReceiverAction, logger) { }
public TopicWorker( IReceiverClient receiverClient, IWorkflowDispatcher workflowDispatcher, IOptions <AzureServiceBusOptions> options, Func <IReceiverClient, Task> disposeReceiverAction, ILogger <TopicWorker> logger) : base(receiverClient, workflowDispatcher, options, disposeReceiverAction, logger) { }
public ObserverClient(ISubscriptionClient client, bool shouldRecieveOnce = true) { this.receiver = client; shouldOnlyReceiveOnce = shouldRecieveOnce; // Register QueueClient's MessageHandler and receive messages in a loop // RegisterOnMessageHandlerAndReceiveMessages(); }
public void SetUp() { _receiver = A.Fake <IServiceBusMessageReceiver>(); _factory = A.Fake <IReceiverClientFactory>(); _receiverClient = A.Fake <IReceiverClient>(); A.CallTo(() => _factory.Create()) .Returns(_receiverClient); _sut = new GenericServiceBusCommunicationListener(null, _factory, _receiver); }
Task OnMessage(IReceiverClient messageReceiver, Message message, CancellationToken cancellationToken) { if (IsStopping) { return(WaitForDeliveryComplete()); } return(_messageReceiver.Handle(message, cancellationToken, context => AddReceiveContextPayloads(context, messageReceiver, message))); }
protected void InitializeReciever(IReceiverClient messageReciever, ILoggerFactory loggerFactory) { MessageReciever = messageReciever; // _serverWaitTime = TimeSpan.FromSeconds(waitTime <= 0 ? DefaultWaitTime : waitTime); _loggerFactory = loggerFactory; _logger = loggerFactory?.CreateLogger(nameof(BusMessageReceiverClient)); }
public ObserverClient(IReceiverClient client) { // Set the receive once flag for Queues // shouldOnlyReceiveOnce = true; this.receiver = client; // Register QueueClient's MessageHandler and receive messages in a loop // RegisterOnMessageHandlerAndReceiveMessages(); }
public PurchasingAzureServiceBusConsumer(IConfiguration config, IMessageBus messageBus) { _configuration = config; _messageBus = messageBus; var serviceBusConnectionString = _configuration.GetValue <string>("AzureServiceBusConnectionString"); productCreatedMessageReceiverClient = new SubscriptionClient(serviceBusConnectionString, prodcutCreatedMessageTopic, subscriptionName); }
public RequestReplySender(ISenderClient sender, IReceiverClient receiver) { _sender = sender; _receiver = receiver; _receiver.RegisterMessageHandler(OnMessageReceived, new MessageHandlerOptions(ExceptionReceivedHandler) { AutoComplete = false }); }
private async Task ProcessSessionMessageAsync(IReceiverClient client, IMessageSession session, Message message, CancellationToken cancellationToken) { _logger.LogInformation("Type : {ClientType}", client.GetType()); try { _logger.LogInformation($"Session :{session.SessionId}"); _logger.LogInformation($"SequenceNumber:{message.SystemProperties.SequenceNumber}"); _logger.LogInformation($"Label :{message.Label}"); _logger.LogInformation($"DeliveryCount :{message.SystemProperties.DeliveryCount}"); string body = Encoding.UTF8.GetString(message.Body); if (body == "1") { await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); // simulate delay _logger.LogError("Error: " + DateTime.UtcNow); throw new Exception("!!!"); } //if (message.Label == nameof(PersonMessage)) //{ // var person = _serializer.Deserialize<PersonMessage>(message.Body); // _logger.LogInformation("person = " + JsonConvert.SerializeObject(person)); //} //else //{ // _logger.LogInformation("other = " + body); //} _logger.LogInformation("OK : " + body); await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); // simulate delay await session.CompleteAsync(message.SystemProperties.LockToken); //await client.CompleteAsync(message.SystemProperties.LockToken); } catch (Exception ex) { _logger.LogError(ex, "Error while Process Message with MessageId: {MessageId}", message.MessageId); if (!session.IsClosedOrClosing) { var properties = new Dictionary <string, object> { { "uhuh", DateTime.UtcNow.ToString() } }; await session.AbandonAsync(message.SystemProperties.LockToken, properties); //await client.AbandonAsync(message.SystemProperties.LockToken); } } }
public void PurgeServiceBusMessagesAsync(IReceiverClient receiverClient, ITestOutputHelper output) { receiverClient.RegisterMessageHandler(async(Microsoft.Azure.ServiceBus.Message message, CancellationToken token) => { // purge message await receiverClient.CompleteAsync(message.SystemProperties.LockToken); }, new MessageHandlerOptions(async args => output.WriteLine(args.Exception.ToString())) { MaxConcurrentCalls = 1, AutoComplete = false }); }
public void StartListening() { activeClient = CreateListener(); activeClient.RegisterMessageHandler((message, handler) => { OnMessageReceived?.Invoke(this, new OnMessageReceivedEventArgs(message)); return(activeClient.CompleteAsync(message.SystemProperties.LockToken)); }, new MessageHandlerOptions(x => Task.CompletedTask)); Console.WriteLine("Started Listening for " + this.GetType().Name); }
public AzureServiceBusReceiver(IReceiverClient receiverClient, bool peekLock, MessageHandlerOptions messageHandlerOptions) { _receiverClient = receiverClient ?? throw new ArgumentNullException(nameof(receiverClient)); _peekLock = peekLock; _messageHandlerOptions = messageHandlerOptions ?? new MessageHandlerOptions(DefaultExceptionReceiverHandler) { AutoComplete = false, MaxAutoRenewDuration = TimeSpan.FromMinutes(1), MaxConcurrentCalls = 1 }; }
async Task OnMessage(IReceiverClient messageReceiver, Message message, CancellationToken cancellationToken) { if (IsStopping) { await WaitAndAbandonMessage(messageReceiver, message).ConfigureAwait(false); return; } using var delivery = Tracker.BeginDelivery(); await _messageReceiver.Handle(message, context => AddReceiveContextPayloads(context, messageReceiver, message)).ConfigureAwait(false); }
public AzServiceBusConsumer(IConfiguration configuration, IMessageBus messageBus, OrderRepository orderRepository) { _configuration = configuration; _orderRepository = orderRepository; // _logger = logger; _messageBus = messageBus; var serviceBusConnectionString = _configuration.GetValue <string>("ServiceBusConnectionString"); checkoutMessageTopic = _configuration.GetValue <string>("CheckoutMessageTopic"); checkoutMessageReceiverClient = new SubscriptionClient(serviceBusConnectionString, checkoutMessageTopic, subscriptionName); }
protected async Task WaitAndAbandonMessage(IReceiverClient receiverClient, Message message) { try { await _deliveryComplete.Task.ConfigureAwait(false); await receiverClient.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false); } catch (Exception exception) { LogContext.Error?.Log(exception, "Abandon message faulted during shutdown: {InputAddress}", _context.InputAddress); } }
protected async Task WaitAndAbandonMessage(IReceiverClient receiverClient, Message message) { try { await _deliveryComplete.Task.ConfigureAwait(false); await receiverClient.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false); } catch (Exception exception) { if (_log.IsErrorEnabled) { _log.Debug($"Stopping receiver, abandoned message faulted: {_context.InputAddress}", exception); } } }