Exemple #1
0
        public async Task <HttpResponseMessage> Send(HttpRequestMessage request, CancellationToken token)
        {
            var options = request.Properties.ContainsKey(NatsQueueClientOption.ConnectionProperty)
                                ? request.Properties[NatsQueueClientOption.ConnectionProperty] as Options
                                : _clientOption.Options;

            if (options == null)
            {
                throw new ArgumentException(
                          $"ConnectionFactory in option or {nameof(request.Properties)} key name {NatsQueueClientOption.ConnectionProperty} must be set");
            }

            var content     = new HttpMessageContent(request);
            var bytesTask   = content.ReadAsByteArrayAsync();
            var correlation = request.Headers.GetCorrelationHeader();
            var connection  = _connection.CreateConnection(options);

            if (correlation != null)
            {
                var responseMsg = await connection.RequestAsync(request.RequestUri.Host, await bytesTask, token);

                var responseMessage = await _responseParser.Parse(responseMsg.Data, token);

                return(responseMessage);
            }

            var bytes = await bytesTask;

            connection.Publish(request.RequestUri.Host, bytes);
            _log.LogTrace("Message to {url} sended", request.RequestUri.Host);

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Exemple #2
0
        /// <inheritdoc />
        public Task Start(RequestDelegate requestDelegate, CancellationToken cancellationToken)
        {
            var connection = _connection.CreateConnection(_options.Options);

            _log.LogTrace("NATS connected. Subscribing to queue {host}", _options.Server.Host);

            _subscription = connection.SubscribeAsync(_options.Server.Host, async(_, args) =>
            {
                try
                {
                    var context = await _converter.Parse(args, new FeatureCollection());

                    if (context != null)
                    {
                        await requestDelegate(context);
                        await _responseProcessed.ProcessResponse(args, context, connection);
                    }
                    else
                    {
                        _log.LogError("Cannot parse context");
                    }
                }
                catch (Exception e)
                {
                    _log.LogError(e, $"Nats server not processed request {args.Message.Subject}");
                }
            });

            _log.LogTrace("NATS server subscribed");
            return(Task.CompletedTask);
        }