Ejemplo n.º 1
0
        /// <summary>
        /// get 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceName"></param>
        /// <param name="webApiPath"></param>
        /// <param name="scheme"></param>
        /// <param name="customHeaders"></param>
        /// <param name="MediaType"></param>
        /// <param name="isBuried"></param>
        /// <returns></returns>
        public T GetWebApi <T>(string serviceName, string webApiPath,
                               string scheme = "http",
                               Dictionary <string, string> customHeaders = null,
                               string MediaType = "application/json",
                               bool isTrace     = false)
        {
            // 接口地址
            var apiUri = GetApiUrl(serviceName, webApiPath, scheme);
            // 追踪信息
            var traceLog = CreateBaseTracer(apiUri, MediaType, isTrace, customHeaders);
            // http请求
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(apiUri),
                Method     = HttpMethod.Get
            };

            request.Headers.Clear();
            request.Headers.Accept.Clear();
            if (customHeaders != null)
            {
                foreach (KeyValuePair <string, string> customHeader in customHeaders)
                {
                    request.Headers.Add(customHeader.Key, customHeader.Value);
                }
            }
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaType));
            traceLog.Request = request.RequestUri.Query;
            try
            {
                var httpResponseMessage = _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).GetAwaiter().GetResult();
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    traceLog.IsSuccess   = true;
                    traceLog.IsException = false;
                    return(ToResult <T>(httpResponseMessage, traceLog));
                }
            }
            catch (Exception ex)
            {
                traceLog.IsException = true;
                _logger.LogError(ex, $"服务{serviceName},路径{webApiPath}接口请求异常");
            }
            finally
            {
                if (isTrace)
                {
                    traceLog.EndTime    = DateTime.Now;
                    traceLog.TimeLength = Math.Round((traceLog.EndTime - traceLog.StartTime).TotalMilliseconds, 4);
                    _tracer.PublishAsync(traceLog).GetAwaiter();
                }
            }
            throw new Exception($"服务{serviceName},路径{webApiPath}接口请求异常");
        }
Ejemplo n.º 2
0
        public async Task Invoke(HttpContext context)
        {
            var trace = new TraceLogs()
            {
                ApiUri      = context?.Request?.GetDisplayUrl(),
                StartTime   = DateTime.Now,
                ContextType = context?.Request?.ContentType
            };

            _tracer.AddHeadersToTracer(context, trace);
            _requestScopedDataRepository.Add(TracerKeys.TraceStoreCacheKey, trace);

            await _next(context);

            trace = _requestScopedDataRepository.Get <TraceLogs>(TracerKeys.TraceStoreCacheKey);
            if (trace != null)
            {
                trace.EndTime    = DateTime.Now;
                trace.TimeLength = Math.Round((trace.EndTime - trace.StartTime).TotalMilliseconds, 4);
                _requestScopedDataRepository.Update(TracerKeys.TraceStoreCacheKey, trace);
                await _tracer.PublishAsync(trace);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// get 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceName"></param>
        /// <param name="webApiPath"></param>
        /// <param name="scheme"></param>
        /// <param name="customHeaders"></param>
        /// <param name="MediaType"></param>
        /// <param name="isBuried"></param>
        /// <returns></returns>
        public T GetWebApi <T>(string serviceName, string webApiPath,
                               string scheme = "http",
                               Dictionary <string, string> customHeaders = null,
                               string MediaType = "application/json",
                               bool isTrace     = false)
        {
            #region 负载寻址
            var _load = _loadBalancerHouse.Get(serviceName).GetAwaiter().GetResult();
            if (_load == null)
            {
                throw new ArgumentNullException(nameof(_load));
            }
            var HostAndPort = _load.Lease().GetAwaiter().GetResult();
            if (HostAndPort == null)
            {
                throw new ArgumentNullException(nameof(HostAndPort));
            }
            string baseAddress = $"{scheme}://{HostAndPort.ToString()}/";
            webApiPath = webApiPath.TrimStart('/');
            #endregion

            #region  游请求头处理
            if (isTrace)
            {
                // 请求头下发,埋点请求头
                if (customHeaders == null)
                {
                    customHeaders = new Dictionary <string, string>();
                }
                var downStreamHeaders = _tracer.DownTraceHeaders(_httpContextAccessor.HttpContext);
                // 合并键值
                customHeaders = customHeaders.Concat(downStreamHeaders).ToDictionary(k => k.Key, v => v.Value);
            }
            #endregion

            #region 请求埋点
            var traceLog = new TraceLogs()
            {
                ApiUri      = $"{baseAddress}{webApiPath}",
                ContextType = MediaType,
                StartTime   = DateTime.Now,
            };
            if (isTrace)
            {
                _tracer.AddHeadersToTracer <TraceLogs>(_httpContextAccessor.HttpContext, traceLog);
                if (customHeaders.TryGetValue(TracerKeys.TraceSeq, out string value))
                {
                    traceLog.ParentSeq = value;
                }
            }
            #endregion

            #region http 请求
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri($"{baseAddress}{webApiPath}"),
                Method     = HttpMethod.Get
            };
            request.Headers.Clear();
            request.Headers.Accept.Clear();
            if (customHeaders != null)
            {
                foreach (KeyValuePair <string, string> customHeader in customHeaders)
                {
                    request.Headers.Add(customHeader.Key, customHeader.Value);
                }
            }
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaType));
            traceLog.Request = request.RequestUri.Query;
            try
            {
                var httpResponseMessage = _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).GetAwaiter().GetResult();
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    traceLog.IsSuccess   = true;
                    traceLog.IsException = false;
                    if (typeof(T) == typeof(byte[]))
                    {
                        return((T)Convert.ChangeType(httpResponseMessage.Content.ReadAsByteArrayAsync().Result, typeof(T)));
                    }
                    if (typeof(T) == typeof(Stream))
                    {
                        return((T)Convert.ChangeType(httpResponseMessage.Content.ReadAsStreamAsync().Result, typeof(T)));;
                    }
                    if (typeof(T) == typeof(String))
                    {
                        var result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                        traceLog.Response = result;
                        return((T)Convert.ChangeType(result, typeof(T)));
                    }
                    else
                    {
                        var result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                        traceLog.Response = result;
                        return(_jsonHelper.DeserializeObject <T>(result));
                    }
                }
            }
            catch (Exception ex)
            {
                traceLog.IsException = true;
                _logger.LogError(ex, $"服务{serviceName},路径{webApiPath}接口请求异常");
            }
            finally
            {
                if (isTrace)
                {
                    traceLog.EndTime    = DateTime.Now;
                    traceLog.TimeLength = Math.Round((traceLog.EndTime - traceLog.StartTime).TotalMilliseconds, 4);
                    _tracer.PublishAsync <TraceLogs>(traceLog).GetAwaiter();
                }
            }
            #endregion

            throw new Exception($"服务{serviceName},路径{webApiPath}接口请求异常");
        }