Exemplo n.º 1
0
        public void Init(Uri uri, DelayOptions options)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _options = options;
            var ordered = options.QueueOptions.GroupBy(x => x.Ttl).OrderBy(x => x.Key).Select(x => x.First()).ToArray();

            _delays = new Dictionary <TimeSpan, RabbitDelayInfo>(ordered.Length);
            RabbitDelayInfo next = null;

            for (int i = ordered.Length - 1; i >= 0; i--)
            {
                var delay = ordered[i];
                var info  = new RabbitDelayInfo
                {
                    Option    = delay,
                    Next      = next,
                    QueueName = QueueNameExtensions.GetQueue(uri, delay.Uri)
                };
                _delays.Add(delay.Ttl, info);
                next = info;
            }

            _first = next;
        }
Exemplo n.º 2
0
 public Sender(IRabbitMQBase rabbitMQBase, ILoggerFactory loggerFactory, IOrderItemsDao orderItemsDao, IOptions <DelayOptions> settings)
 {
     try
     {
         this.processedQueueName = "ORDERPROCESSED_QUEUE";
         this.logger             = loggerFactory.CreateLogger <Sender>();
         this.connection         = rabbitMQBase.Connection;
         this.processedChannel   = connection.CreateModel();
         this.processedChannel.QueueDeclare(queue: processedQueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
         this.orderItemsDao = orderItemsDao;
         this.delayOptions  = settings?.Value ?? throw new ArgumentNullException(nameof(settings));
     }
     catch (Exception ex)
     {
         this.logger.LogError($"Message: {ex.Message}, Source: {ex.Source}, StackTrace: {ex.StackTrace}");
     }
 }
 public DelayTest(DelayOptions options, DelayMetrics metrics) : base(options, metrics)
 {
 }
Exemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = new RabbitConnection
            {
                ConnectionFactory = new ConnectionFactory
                {
                    HostName = "127.0.0.1",
                    Port     = 5672,
                    UserName = "******",
                    Password = "******"
                }
            };


            var clientOption = new RabbitClientOptions
            {
                ClientName   = Guid.NewGuid().ToString("N"),
                ClientUnique = Guid.NewGuid().ToString("N").Substring(0, 6),
                Connection   = connection
            };

            services.AddRabbitClient(provider => clientOption);
            //services.AddHttpClient<PersonalClient>().ConfigurePrimaryRabbitMessageHandler(connection.ConnectionFactory, provider => clientOption);

            //services.AddHttpClient<PersonalClient>().ConfigurePrimaryHttpMessageHandler(provider => provider.GetService<NatsMessageHandler>());

            //services.AddHttpClient<PersonalClient>().ConfigurePrimaryKafkaMessageHandler(provider => new KafkaOptions
            //{
            //	ProducerConfig = new ProducerConfig { BootstrapServers = "localhost:9092" },
            //	ConsumerConfig = new ConsumerConfig
            //	{
            //		ClientId = "test",
            //		GroupId = "test-consumer-group",
            //		BootstrapServers = "localhost:9092",
            //		AutoOffsetReset = AutoOffsetReset.Earliest
            //	}
            //});
            //var options = NATS.Client.ConnectionFactory.GetDefaultOptions();
            //options.Name = "localhost";
            //options.Servers = new[] { "nats://localhost:4222" };

            //services.AddNatsClient(provider => new NatsQueueClientOption
            //{
            //	Options = options
            //});

            //	adminBuilder.
            //	.AddNatsServer(provider => new NatsServerOption
            //{
            //	Options = options,
            //	Server = new Uri("nats://localhost")
            //});
            //services.AddKafkaServer(provider => new KafkaServerOption
            //{
            //	Server = new List<Uri> {new Uri("kafka://localhost")},
            //	ProducerConfig = new ProducerConfig {BootstrapServers = "localhost:9092"},
            //	ConsumerConfig = new ConsumerConfig
            //	{
            //		ClientId = "personal-area",
            //		GroupId = "test-consumer-group",
            //		BootstrapServers = "localhost:9092",
            //		AutoOffsetReset = AutoOffsetReset.Earliest
            //	}
            //});
            services.AddRabbitServer(new RabbitServerOptions
            {
                Connection   = connection,
                DelayOptions = new DelayOptions
                {
                    QueueOptions = DelayOptions.CreateInterval().Take(3).ToList()
                },
                Queue = new AppQueueOption
                {
                    Uri = new Uri("rabbitmq://localhost")
                }
            });
            services.Configure <RabbitMessageHandler>(handler =>
            {
                handler.Factory = null;
            });
            services.AddControllers();
        }
Exemplo n.º 5
0
        /// <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);
        }