Пример #1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="redisManager"></param>
 /// <param name="dataBaseOptionService"></param>
 public RedisOptionService(
     IRedisManager redisManager
     , IDataBaseOptionService dataBaseOptionService)
 {
     _redisManager          = redisManager;
     _dataBaseOptionService = dataBaseOptionService;
 }
Пример #2
0
        public void Init()
        {
            List <string> csredisConns = new List <string>();
            string        password     = "******";
            int           defaultDb    = 0;
            string        ssl          = "";
            string        keyPrefix    = "";
            int           writeBuffer  = 10240;
            int           poolsize     = 20;
            int           timeout      = 10;

            csredisConns.Add($"198.185.15.16:6379,password={password},defaultDatabase={defaultDb},poolsize={poolsize},ssl={ssl},writeBuffer={writeBuffer},prefix={keyPrefix},preheat={1},idleTimeout={timeout},testcluster={true}");

            CSRedis.CSRedisClient csredis;

            try
            {
                csredis = new CSRedis.CSRedisClient(null, csredisConns.ToArray());
            }
            catch (Exception ex)
            {
                throw new ArgumentException($"请检查是否为非密码模式,Password必须为空字符串;请检查Database是否为0,只能在非集群模式下才可配置Database大于0;{ex}");
            }

            RedisHelper.Initialization(csredis);

            _redisDatabase = new CsRedisManager(new RedisCacheOption
            {
            }, new NetPro.CsRedis.SystemTextJsonSerializer());
        }
Пример #3
0
        private Azure(RestClient restClient, string subscriptionId, string tenantId, IAuthenticated authenticated)
        {
            resourceManager          = ResourceManager.Fluent.ResourceManager.Authenticate(restClient).WithSubscription(subscriptionId);
            storageManager           = StorageManager.Authenticate(restClient, subscriptionId);
            computeManager           = ComputeManager.Authenticate(restClient, subscriptionId);
            networkManager           = NetworkManager.Authenticate(restClient, subscriptionId);
            batchManager             = BatchManager.Authenticate(restClient, subscriptionId);
            keyVaultManager          = KeyVaultManager.Authenticate(restClient, subscriptionId, tenantId);
            trafficManager           = TrafficManager.Fluent.TrafficManager.Authenticate(restClient, subscriptionId);
            dnsZoneManager           = DnsZoneManager.Authenticate(restClient, subscriptionId);
            sqlManager               = SqlManager.Authenticate(restClient, subscriptionId);
            redisManager             = RedisManager.Authenticate(restClient, subscriptionId);
            cdnManager               = CdnManager.Authenticate(restClient, subscriptionId);
            appServiceManager        = AppServiceManager.Authenticate(restClient, subscriptionId, tenantId);
            searchManager            = SearchManager.Authenticate(restClient, subscriptionId);
            serviceBusManager        = ServiceBusManager.Authenticate(restClient, subscriptionId);
            containerInstanceManager = ContainerInstanceManager.Authenticate(restClient, subscriptionId);
            registryManager          = RegistryManager.Authenticate(restClient, subscriptionId);
            containerServiceManager  = ContainerServiceManager.Authenticate(restClient, subscriptionId);
            cosmosDBManager          = CosmosDBManager.Authenticate(restClient, subscriptionId);
            authorizationManager     = AuthorizationManager.Authenticate(restClient, subscriptionId);
            msiManager               = MsiManager.Authenticate(restClient, subscriptionId);
            batchAIManager           = BatchAIManager.Authenticate(restClient, subscriptionId);
            monitorManager           = MonitorManager.Authenticate(restClient, subscriptionId);
            eventHubManager          = EventHubManager.Authenticate(restClient, subscriptionId);

            SubscriptionId     = subscriptionId;
            this.authenticated = authenticated;
        }
Пример #4
0
 public BatchController(
     IMessagePublisher messagePublisher,
     IRedisManager redisManager)
 {
     m_MessagePublisher = messagePublisher;
     m_RedisManager     = redisManager;
 }
Пример #5
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="xXXService"></param>
 /// <param name="userApi"></param>
 //[FromServices]
 public WeatherForecastController(ILogger logger
                                  , IXXXService xXXService
                                  , IExampleProxy userApi
                                  , IRedisManager redisManager)
 {
     _logger       = logger;
     _xXXService   = xXXService;
     _userApi      = userApi;
     _redisManager = redisManager;
 }
Пример #6
0
        public Resolution(IRedisManager redis)
        {
            _redis = redis;

            NormalValue = 0.03;//允许的误差值

            L1 = 0.03;
            L2 = 0.1;
            L3 = 0.15;

            //TODO 获取天气情况
        }
Пример #7
0
        public async Task Invoke(HttpContext context, IRedisManager redisManager)
        {
            try
            {
                var requestMessage = new HttpRequestMessage();
                var requestMethod  = context.Request.Method;

                if (!HttpMethods.IsGet(requestMethod) && !HttpMethods.IsHead(requestMethod) && !HttpMethods.IsDelete(requestMethod) && !HttpMethods.IsTrace(requestMethod))
                {
                    var streamContent = new StreamContent(context.Request.Body);
                    requestMessage.Content = streamContent;
                }

                // All request headers and cookies must be transferend to remote server. Some headers will be skipped
                foreach (var header in context.Request.Headers)
                {
                    if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
                    {
                        requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                    }
                }

                string uriString = GetUri(context, redisManager);

                //recreate remote url
                requestMessage.RequestUri = new Uri(uriString);
                requestMessage.Method     = new HttpMethod(context.Request.Method);
                var responseMessage = await redisManager.GetConnection().SendAsync(requestMessage);


                context.Response.StatusCode = (int)responseMessage.StatusCode;
                foreach (var header in responseMessage.Headers)
                {
                    context.Response.Headers[header.Key] = header.Value.ToArray();
                }

                foreach (var header in responseMessage.Content.Headers)
                {
                    context.Response.Headers[header.Key] = header.Value.ToArray();
                }


                //tell to the browser that response is not chunked
                //context.Response.Headers.Remove("transfer-encoding");
                await responseMessage.Content.CopyToAsync(context.Response.Body);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
Пример #8
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="next"></param>
 /// <param name="iLogger"></param>
 /// <param name="requestAnalysisOption"></param>
 /// <param name="memorycache"></param>
 /// <param name="redisManager"></param>
 /// <param name="redisCacheOption"></param>
 /// <param name="httpContextAccessor"></param>
 public RequestAnalysisMiddleware(RequestDelegate next,
                                  ILogger <RequestAnalysisMiddleware> iLogger,
                                  RequestAnalysisOption requestAnalysisOption,
                                  IMemoryCache memorycache,
                                  IRedisManager redisManager,
                                  RedisCacheOption redisCacheOption,
                                  IHttpContextAccessor httpContextAccessor)
 {
     _next    = next;
     _iLogger = iLogger;
     _requestAnalysisOption = requestAnalysisOption;
     _memorycache           = memorycache;
     _redisManager          = redisManager;
     _redisCacheOption      = redisCacheOption;
     _httpContextAccessor   = httpContextAccessor;
 }
Пример #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="next"></param>
        /// <param name="iLogger"></param>
        /// <param name="requestAnalysisOption"></param>
        /// <param name="memorycache"></param>
        /// <param name="redisManager"></param>
        /// <param name="redisCacheOption"></param>
        /// <param name="httpContextAccessor"></param>
        public RequestAnalysisMiddleware(RequestDelegate next,
                                         ILogger <RequestAnalysisMiddleware> iLogger,
                                         RequestAnalysisOption requestAnalysisOption,
                                         IMemoryCache memorycache,
#pragma warning disable CS0618 // Type or member is obsolete
                                         IRedisManager redisManager,
#pragma warning restore CS0618 // Type or member is obsolete
                                         RedisCacheOption redisCacheOption,
                                         IHttpContextAccessor httpContextAccessor)
        {
            _next    = next;
            _iLogger = iLogger;
            _requestAnalysisOption = requestAnalysisOption;
            _memorycache           = memorycache;
            _redisManager          = redisManager;
            _redisCacheOption      = redisCacheOption;
            _httpContextAccessor   = httpContextAccessor;
        }
Пример #10
0
        public LedSendServer(IRedisManager redis, IResolution resolution, IDTCache cache)
        {
            _serverUrl = ConfigurationManager.ConnectionStrings["Signalr"].ConnectionString;

            _log = LogManager.GetLogger(typeof(LedSendServer));

            _timer = new Timer(10000)
            {
                Enabled = true
            };

            _redis = redis;

            _resolution = resolution;

            fontList = _redis.Get <List <FontLibrary> >("Default:Kylin:LED:FontLibrary");

            _cache = cache;
        }
Пример #11
0
 public RedisRateLimiter(IRedisManager redisManager)
 {
     this._redisManager = redisManager;
 }
Пример #12
0
 public DefaultLoginRegistry(IRedisManager redisManager)
 {
     _redisManager = redisManager;
 }
Пример #13
0
 public DailyTextManager(IDailyTextManagerQuery dailyTextManagerQuery, IRedisManager redisManager)
 {
     _dailyTextManagerQuery = dailyTextManagerQuery;
     _redisManager          = redisManager;
     _logger = LogManager.GetCurrentClassLogger();
 }
Пример #14
0
 public AuthenticationManager(ILogService logger, IRedisManager redisManager)
 {
     _logger       = logger;
     _redisManager = redisManager;
 }
Пример #15
0
 public AppConfigurationTest()
 {
     Init();
     RedisManager = Resolver.Resolve <IRedisManager>();
     Application  = Resolver.Resolve <IApplication>();
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            IServiceProvider serviceProvider = context.HttpContext.RequestServices;
            var responseCacheOption          = serviceProvider.GetService <ResponseCacheOption>();

            //配置存在且配置关闭或者持续时长等于0,即忽略响应缓存
            if ((responseCacheOption != null && !responseCacheOption.Enabled) || Duration == 0)
            {
                goto gotoNext;
            }
            context.HttpContext.Request.EnableBuffering();
            var           _logger        = serviceProvider.GetRequiredService <ILogger <PostResponseCacheAttribute> >();
            var           _configuration = serviceProvider.GetRequiredService <IConfiguration>();
            var           _memorycache   = serviceProvider.GetService <IMemoryCache>();
            IRedisManager _redisManager  = null;

            if ((responseCacheOption != null && responseCacheOption.Cluster) || Cluster)
            {
                _redisManager = serviceProvider.GetService <IRedisManager>();
                if (_redisManager == null)
                {
                    throw new ArgumentNullException(nameof(IMemoryCache), "Post响应已启用集群模式,缓存依赖IRedisManager,请services.AddRedisManager()注入IRedisManager后再使用[PostResponseCache]");
                }
            }
            if (_memorycache == null)
            {
                throw new ArgumentNullException(nameof(IMemoryCache), "Post响应缓存依赖IMemoryCache,请services.AddMemoryCache()注入IMemoryCache后再使用[PostResponseCache]");
            }
            //标识已触发过响应缓存,防止中间件再次触发
            _memorycache.Set($"PostResponseCache_{context.HttpContext.Request.Path}", "标识已触发过响应缓存,防止中间件再次触发", new MemoryCacheEntryOptions {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
            });

            var _requestCacheData = serviceProvider.GetService <RequestCacheData>();

            if (_requestCacheData == null)
            {
                throw new ArgumentNullException(nameof(IMemoryCache), "Post响应缓存依赖ResponseCacheData,请调用services.AddShareRequestBody()注入后再使用[PostResponseCache]");
            }

            var token = context.HttpContext.RequestAborted.Register(async() =>
            {
                await Task.CompletedTask;
                return;
            });

            var descriptor = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;

            var attribute = (IgnorePostResponseCacheAttribute)descriptor.MethodInfo.GetCustomAttributes(typeof(IgnorePostResponseCacheAttribute), true).FirstOrDefault();

            if (attribute != null)
            {
                //记录忽略的路由,中间件跳过
                _memorycache.Set($"IgnorePostResponseCache_{context.HttpContext.Request.Path}", true, new MemoryCacheEntryOptions {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
                });
                goto gotoNext;
            }

            if (context.HttpContext.Request.Method.Equals("get", StringComparison.OrdinalIgnoreCase) || context.HttpContext.Request.Method.Equals("head", StringComparison.OrdinalIgnoreCase))
            {
                goto gotoNext;
            }
            else
            {
                var convertedDictionatry = context.HttpContext.Request.Query.ToDictionary(s => s.Key.ToLower(), s => s.Value);

                if (IgnoreVaryByQueryKeys == null || !IgnoreVaryByQueryKeys.Any())
                {
                    if (responseCacheOption.IgnoreVaryByQueryKeys.Any())
                    {
                        IgnoreVaryByQueryKeys = responseCacheOption.IgnoreVaryByQueryKeys.ToArray();
                    }
                }

                foreach (var item in IgnoreVaryByQueryKeys ?? new string[0])
                {
                    if (convertedDictionatry.ContainsKey(item.ToLower()))
                    {
                        convertedDictionatry.Remove(item.ToLower());
                    }
                }

                StringBuilder requestStrKey = new StringBuilder(context.HttpContext.Request.Path);
                foreach (var item in convertedDictionatry)
                {
                    requestStrKey.Append($"{item.Key}{item.Value}");
                }

                string bodyValue;
                if (_requestCacheData == null || string.IsNullOrEmpty(_requestCacheData.Body))
                {
                    bodyValue = await Common.ReadAsString(context.HttpContext);

                    _requestCacheData = new RequestCacheData {
                        Body = bodyValue
                    };
                }
                else
                {
                    bodyValue = _requestCacheData.Body;
                }
                if (!string.IsNullOrEmpty(bodyValue) && !"null".Equals(bodyValue))
                {
                    //非Get请求body有值才被缓存,其他默认不缓存,防止body读取失败导致缓存异常
                    bodyValue = Regex.Replace(bodyValue, @"\s(?=([^""]*""[^""]*"")*[^""]*$)", string.Empty);
                    bodyValue = bodyValue.Replace("\r\n", "").Replace(" : ", ":").Replace("\n  ", "").Replace("\n", "").Replace(": ", ":").Replace(", ", ",");

                    requestStrKey.Append($"body{bodyValue}");
                    ResponseCacheData cacheResponseBody = null;
                    if (Cluster)
                    {
                        cacheResponseBody = _redisManager.Get <ResponseCacheData>($"NetProPostResponse:{requestStrKey}");
                    }
                    else
                    {
                        cacheResponseBody = _memorycache.Get <ResponseCacheData>($"NetProPostResponse:{requestStrKey}");
                    }

                    if (cacheResponseBody != null && !context.HttpContext.RequestAborted.IsCancellationRequested)
                    {
                        if (!context.HttpContext.Response.HasStarted)
                        {
                            _logger.LogInformation($"触发PostResponseCacheAttribute本地缓存");
                            switch (ResponseMode)
                            {
                            case ResponseMode.Cache:
                                context.HttpContext.Response.StatusCode  = cacheResponseBody.StatusCode;
                                context.HttpContext.Response.ContentType = cacheResponseBody.ContentType;
                                await context.HttpContext.Response.WriteAsync(cacheResponseBody.Body);

                                await Task.CompletedTask;
                                return;

                            case ResponseMode.Error:
                                if (cacheResponseBody.StatusCode == 200)
                                {
                                    //TODO确定StatusCode与Headers响应的先后顺序
                                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
                                    context.HttpContext.Response.Headers.Add("Kestrel-ResponseMode", $"{ResponseMode}");
                                    context.HttpContext.Response.ContentType = cacheResponseBody.ContentType;
                                    await context.HttpContext.Response.WriteAsync(JsonSerializer.Serialize(new
                                    {
                                        Code = -1,
                                        Msg  = $"{Message}"
                                    }, new JsonSerializerOptions
                                    {
                                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All)
                                    }), Encoding.UTF8);

                                    await Task.CompletedTask;
                                    return;
                                }
                                else
                                {
                                    context.HttpContext.Response.StatusCode  = cacheResponseBody.StatusCode;
                                    context.HttpContext.Response.ContentType = cacheResponseBody.ContentType;
                                    await context.HttpContext.Response.WriteAsync(cacheResponseBody.Body);

                                    await Task.CompletedTask;
                                    return;;
                                }
                            }
                        }
                        else
                        {
                            _logger.LogError($"StatusCode无法设置,因为响应已经启动,位置为:触发本地缓存开始赋值[responsecache2]");
                            await Task.CompletedTask;
                            return;
                        }
                    }
                    else if (!context.HttpContext.RequestAborted.IsCancellationRequested)
                    {
                        try
                        {
                            var actionResult = await next();

                            dynamic responseResult = (dynamic)actionResult.Result;
                            if (actionResult.Exception != null)
                            {
                                // 过滤器中await next();执行的始终是Action而不是下一个过滤器或者中间件
                                await Task.CompletedTask;
                                return;
                            }
                            if (responseResult == null)
                            {
                                await Task.CompletedTask;
                                return;
                            }

                            if (responseResult.GetType().Name == "EmptyResult")
                            {
                                await Task.CompletedTask;
                                return;
                            }

                            string body = string.Empty;
                            if (responseResult as Microsoft.AspNetCore.Mvc.ObjectResult != null)
                            {
                                body = JsonSerializer.Serialize(responseResult.Value, new JsonSerializerOptions
                                {
                                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All)
                                });
                            }

                            if (Cluster)
                            {
                                _redisManager.Set($"NetProPostResponse:{requestStrKey}", new ResponseCacheData
                                {
                                    Body        = body,
                                    ContentType = "application/json",
                                    StatusCode  = responseResult.StatusCode ?? 200,
                                }, TimeSpan.FromSeconds(Duration));
                            }
                            else
                            {
                                _memorycache.Set($"NetProPostResponse:{requestStrKey}", new ResponseCacheData
                                {
                                    Body        = body,
                                    ContentType = "application/json",
                                    StatusCode  = responseResult.StatusCode ?? 200,
                                }, TimeSpan.FromSeconds(Duration));
                            }
                        }
                        catch (Exception ex)
                        {
                            await Task.CompletedTask;
                            return;
                        }
                        await Task.CompletedTask;
                        return;
                    }
                    else if (context.HttpContext.RequestAborted.IsCancellationRequested)
                    {
                        await Task.CompletedTask;
                        return;
                    }
                }
                else if (!context.HttpContext.RequestAborted.IsCancellationRequested)
                {
                    goto gotoNext;
                }
                else
                {
                    await Task.CompletedTask;
                    return;
                }
            }

gotoNext:
            await next();
        }
Пример #17
0
 public DataCollectController(IRedisManager redisManager)
 {
     _redisManager = redisManager;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:EasyRateLimit.RateLimitHandler"/> class.
 /// </summary>
 /// <param name="redisManager">Redis manager.</param>
 public RateLimitHandler(IRedisManager redisManager)
 {
     this._redisManager = redisManager;
 }
Пример #19
0
 public BlogService(IRedisManager redisManager)
 {
     this.redisManager = redisManager;
 }
Пример #20
0
 public BasketRepository(IRedisManager redisManager)
 {
     _redisManager = redisManager;
 }
Пример #21
0
 private static string GetUri(HttpContext context, IRedisManager redisManager)
 {
     return($"{redisManager.GetBaseAddress()}/{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}");
 }
Пример #22
0
 public ValueController(ICaching caching, IRedisManager redisManager, IAdvertisementServer iadservice)
 {
     _cach         = caching;
     redisManager_ = redisManager;
     _server       = iadservice;
 }
Пример #23
0
        /// <summary>
        /// Post:(从头排序后+body json整体 )hash
        /// </summary>
        /// <param name="context"></param>
        /// <param name="responseCacheData">自定义对象不能ctor注入</param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context, ResponseCacheData responseCacheData, RequestCacheData requestCacheData)
        {
            context.Request.EnableBuffering();
            var token = context.RequestAborted.Register(async() =>
            {
                await Task.CompletedTask;
                return;
            });

            var endpoint = context.GetEndpoint();

            if (endpoint != null)
            {
                if (endpoint.Metadata
                    .Any(m => m is IgnorePostResponseCacheAttribute))
                {
                    goto gotoNext;
                }
            }

            if (context.Request.Method.Equals("get", StringComparison.OrdinalIgnoreCase) ||
                context.Request.Method.Equals("head", StringComparison.OrdinalIgnoreCase) ||
                _memorycache.TryGetValue($"PostResponseCache_{context.Request.Path}", out object _tempIgnoe) ||
                _memorycache.TryGetValue($"IgnorePostResponseCache_{context.Request.Path}", out object _temp))
            {
                goto gotoNext;
            }
            else
            {
                var convertedDictionatry = context.Request.Query.ToDictionary(s => s.Key.ToLower(), s => s.Value);

                foreach (var item in _responseCacheOption?.IgnoreVaryByQueryKeys ?? new List <string>())
                {
                    if (convertedDictionatry.ContainsKey(item.ToLower()))
                    {
                        convertedDictionatry.Remove(item.ToLower());
                    }
                }

                StringBuilder requestStrKey = new StringBuilder(context.Request.Path);
                foreach (var item in convertedDictionatry)
                {
                    requestStrKey.Append($"{item.Key}{item.Value}");
                }

                string bodyValue;
                if (requestCacheData == null || string.IsNullOrEmpty(requestCacheData.Body))
                {
                    bodyValue = await Common.ReadAsString(context);

                    requestCacheData = new RequestCacheData {
                        Body = bodyValue
                    };
                }
                else
                {
                    bodyValue = requestCacheData.Body;
                }
                if (!string.IsNullOrEmpty(bodyValue) && !"null".Equals(bodyValue))
                {
                    //非Get请求body有值才被缓存,其他默认不缓存,防止body读取失败导致缓存异常
                    bodyValue = Regex.Replace(bodyValue, @"\s(?=([^""]*""[^""]*"")*[^""]*$)", string.Empty);
                    bodyValue = bodyValue.Replace("\r\n", "").Replace(" : ", ":").Replace("\n  ", "").Replace("\n", "").Replace(": ", ":").Replace(", ", ",");

                    requestStrKey.Append($"body{bodyValue}");
                    ResponseCacheData cacheResponseBody = null;
                    IRedisManager     _redisManager     = null;
                    if (_responseCacheOption.Cluster)
                    {
                        _redisManager = context.RequestServices.GetService <IRedisManager>();
                        if (_redisManager == null)
                        {
                            throw new ArgumentNullException(nameof(RedisCacheOption), $"PostResponseCache组件在集群模式下未检测到注入NetPro.CsRedis组件,请检查是否遗漏{nameof(RedisCacheOption)}配置节点");
                        }
                        cacheResponseBody = _redisManager.Get <ResponseCacheData>($"NetProPostResponse:{requestStrKey}");
                    }
                    else
                    {
                        cacheResponseBody = _memorycache.Get <ResponseCacheData>($"NetProPostResponse:{requestStrKey}");
                    }

                    if (cacheResponseBody != null && !context.RequestAborted.IsCancellationRequested)
                    {
                        //https://stackoverflow.com/questions/45675102/asp-net-core-middleware-cannot-set-status-code-on-exception-because-response-ha
                        if (!context.Response.HasStarted)
                        {
                            context.Response.StatusCode  = cacheResponseBody.StatusCode;
                            context.Response.ContentType = cacheResponseBody.ContentType;
                            await context.Response.WriteAsync(cacheResponseBody.Body);

                            _iLogger.LogInformation($"触发PostResponseCacheMiddleware本地缓存");
                            //直接return可避免此错误 :OnStarting cannot be set because the response has already started.
                            await Task.CompletedTask;
                            return;
                        }
                        else
                        {
                            _iLogger.LogError($"StatusCode无法设置,因为响应已经启动,位置为:触发本地缓存开始赋值[responsecache2]");
                            await Task.CompletedTask;
                            return;
                        }
                    }
                    else if (!context.RequestAborted.IsCancellationRequested)
                    {
                        Stream originalBody = context.Response.Body;
                        try
                        {
                            using (var memStream = new MemoryStream())
                            {
                                context.Response.Body = memStream;

                                await _next(context);

                                memStream.Position = 0;
                                string responseBody = new StreamReader(memStream).ReadToEnd();
                                responseCacheData = new ResponseCacheData
                                {
                                    Body        = responseBody,
                                    ContentType = context.Response.ContentType,
                                    StatusCode  = context.Response.StatusCode
                                };
                                memStream.Position = 0;
                                await memStream.CopyToAsync(originalBody);

                                if (_responseCacheOption.Cluster)
                                {
                                    _redisManager.Set($"NetProPostResponse:{requestStrKey}", new ResponseCacheData
                                    {
                                        Body        = responseBody,
                                        ContentType = context.Response.ContentType,
                                        StatusCode  = context.Response.StatusCode
                                    }, TimeSpan.FromSeconds(_responseCacheOption.Duration));
                                }
                                else
                                {
                                    _memorycache.Set <ResponseCacheData>($"NetProPostResponse:{requestStrKey}", new ResponseCacheData
                                    {
                                        Body        = responseBody,
                                        ContentType = context.Response.ContentType,
                                        StatusCode  = context.Response.StatusCode
                                    }, TimeSpan.FromSeconds(_responseCacheOption.Duration));
                                }
                            }
                            await Task.CompletedTask;
                            return;
                        }
                        finally
                        {
                            context.Response.Body = originalBody;
                        }
                    }
                    else if (context.RequestAborted.IsCancellationRequested)
                    {
                        await Task.CompletedTask;
                        return;
                    }
                }
                else if (!context.RequestAborted.IsCancellationRequested)
                {
                    goto gotoNext;
                }
                else
                {
                    await Task.CompletedTask;
                    return;
                }
            }

gotoNext:
            await _next(context);
        }
Пример #24
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="redisConnection">redis</param>
 public ServiceDirectoryProxy(string redisConnection)
 {
     _redisManager = new RedisManager(redisConnection);
 }
Пример #25
0
 public ChatHub(IRedisManager redisManager)
 {
     _redisManager = redisManager;
 }
Пример #26
0
 public RedisProvide()
 {
     _cache = new DT.Data.Core.Redis.RedisProvide();
 }
 public RedisCounterStore(IRedisManager manger)
 {
     this._manager = manger;
 }
Пример #28
0
 public RedisManagerTest()
 {
     Init();
     RedisManager = Resolver.Resolve <IRedisManager>();
     Application  = Resolver.Resolve <IApplication>();
 }
Пример #29
0
 public DailyTextManager(IDailyTextManagerQuery dailyTextManagerQuery, IRedisManager redisManager)
 {
     _dailyTextManagerQuery = dailyTextManagerQuery;
     _redisManager = redisManager;
     _logger = LogManager.GetCurrentClassLogger();
 }
Пример #30
0
 public ScopeTest(IRedisManager redisManager)
 {
     RedisManager_ = redisManager;
 }
Пример #31
0
 public DashBoardController(IHubContext <ChatHub> hubContext, IRedisManager redisManager, ICapPublisher capPublisher)
 {
     _hubContext   = hubContext;
     _redisManager = redisManager;
     _capPublisher = capPublisher;
 }