public RabbitHandler(IRabbitConnectionFactory connectionFactory) { listeners = new Dictionary <string, Func <object, Task> >(); _connection = connectionFactory.CreateConnection(); InitializeListeningChannel(); InitializeDeadLetterQueue(); InitializeSubscribers(); RegisterConsumer(); }
public virtual async Task Publish(object message, string routingKey, string correlationId) { await Task.Run(() => { using (IModel model = _connectionFactory.CreateConnection().CreateModel()) { model.ExchangeDeclare(MessageBusConfiguration.ExchangeName, "topic", true); IBasicProperties basicProperties = model.CreateBasicProperties(); basicProperties.DeliveryMode = 2; basicProperties.Headers = new Dictionary <string, object>() { { nameof(correlationId), correlationId } }; var body = Encoding.UTF8.GetBytes(message.ToString()); model.BasicPublish(MessageBusConfiguration.ExchangeName, routingKey, basicProperties, body); } }); }
private Task Init(ConnectionFactory factory) { if (!_option.IsConfiguredClient) { throw new ArgumentException($"{nameof(RabbitClientOptions)} must be configured {nameof(RabbitClientOptions.ClientUnique)} and {nameof(RabbitClientOptions.ClientName)}"); } var key = DefaultRabbitConnectionFactory.CreateKey(factory); if (_channels.TryGetValue(key, out _)) { return(Task.CompletedTask); } lock (objLock) { try { if (_channels.TryGetValue(key, out _)) { return(Task.CompletedTask); } var connection = _connectionFactory.CreateConnection(factory); var channel = connection.CreateModel(); if (!_channels.TryAdd(key, channel)) { throw new Exception($"Error initialize response channel {key}"); } var queue = _option.ClientQueue; _log.LogTrace($"create consumer {nameof(EventingBasicConsumer)}"); channel.QueueDeclare(queue, true); _consumer = new EventingBasicConsumer(channel); _consumer.Received += OnReceived; _consumer.Shutdown += (sender, args) => { _log.LogCritical($"ConnectionFactory Shutdown. {args.ReplyText}"); }; channel.BasicConsume(queue: queue, autoAck: true, consumer: _consumer); } catch (Exception e) { _log.LogError(e, "Error create consumer response"); if (_consumer != null) { _consumer.Received -= OnReceived; } _channels.TryRemove(key, out var channel); channel?.Dispose(); } return(Task.CompletedTask); } }
public RabbitService(IOptions <RabbitSettings> rabbitSettings, IRabbitConnectionFactory rabbitConnectionFactory) { _conn = rabbitConnectionFactory.CreateConnection(rabbitSettings.Value); _channel = _conn.CreateModel(); _channel.ExchangeDeclare(exchange: "users", type: ExchangeType.Fanout); }
/// <inheritdoc cref="IRabbitQueueClient" /> public async Task <HttpResponseMessage> Send(HttpRequestMessage request, CancellationToken token) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (request.RequestUri == null) { throw new ArgumentNullException(nameof(request.RequestUri)); } var routing = request.RequestUri.Host; var connectioFactory = _option.Connection?.ConnectionFactory; if (request.Properties.TryGetValue(RabbitRequestOption.RequestProperty, out var requestObjectOption)) { _log.LogTrace("Rabbit Request configured"); if (requestObjectOption is RabbitRequestOption requestOption) { if (requestOption.ConnectionFactory != null) { connectioFactory = requestOption.ConnectionFactory; } if (requestOption.Delay != TimeSpan.Zero) { var delay = DelayOptions.CreateDelayOption(requestOption.Delay); routing = string.Join("/", routing, delay.Uri.ToString()); } } else { throw new ArgumentException( $"Incorrect configured {nameof(HttpRequestMessage)} property {RabbitRequestOption.RequestProperty}. is not set type {nameof(RabbitRequestOption)}"); } } if (connectioFactory == null) { throw new ArgumentException($"ConnectionFactory in option or {nameof(request.Properties)} key name {RabbitRequestOption.RequestProperty}.{nameof(RabbitRequestOption.ConnectionFactory)} must be set"); } var connection = _connectionFactory.CreateConnection(connectioFactory); using var channel = connection.CreateModel(); var props = channel.CreateBasicProperties().Prepare(request); if (_option.ClientName != null) { props.AppId = _option.ClientName; } Task <HttpResponseMessage> prepared; var body = new byte[0]; if (request.Content != null) { body = await request.Content.ReadAsByteArrayAsync(); } var correlationId = request.Headers.GetCorrelationHeader(); if (correlationId != null) { if (!_option.IsConfiguredClient) { _log.LogWarning($"{nameof(_option.ClientName)} and {nameof(_option.ClientUnique)} required configure. Answer for correlationId {correlationId} not be received!"); prepared = AsyncResponse; } else { props.CorrelationId = correlationId; props.ReplyToAddress = new PublicationAddress(RabbitConsts.Schema, "", _option.ClientQueue); prepared = _queuePrepared.Prepare(correlationId, connectioFactory, token); } } else { prepared = AsyncResponse; } token.ThrowIfCancellationRequested(); _log.LogTrace("rabbit {url}. route: {queue}. request {path}, length {length} sending.... ", connection.Endpoint.ToString(), routing, request.RequestUri.Host + request.RequestUri.PathAndQuery, body.Length); channel.BasicPublish(DefaultExchange, routing, props, body); _log.LogTrace("route: {queue}. request sended", routing); return(await prepared); }