Beispiel #1
0
        public static void Set <T>(string key, T value, TimeSpan timeSpan, bool async = true, bool isCacheFile = false)
        {
            AppCache.Set(key, value, TimeSpan.FromSeconds(AutoAppCacheSeconds));

            if (async)
            {
                Task.Run(async() =>
                {
                    await Task.Delay(1);
                    if (isCacheFile)
                    {
                        var cacheResultJson = ConvertJson(value);
                        var cacheFileName   = CacheFile(key, cacheResultJson, typeof(T).FullName);
                    }
                    else
                    {
                        RedisCache.Set(key, value, timeSpan);
                        //RedisCache.Set3(key, value, timeSpan);
                    }
                });
            }
            else
            {
                if (isCacheFile)
                {
                    var cacheResultJson = ConvertJson(value);
                    var cacheFileName   = CacheFile(key, cacheResultJson, typeof(T).FullName);
                }
                else
                {
                    RedisCache.Set(key, value, timeSpan);
                    //RedisCache.Set3(key, value, timeSpan);
                }
            }
        }
Beispiel #2
0
        public static dynamic Get <T>(string key, double restoreAppCahcheSeconds = AutoAppCacheSeconds)
        {
            AppCache.TryGetValue <T>(key, out var value);

            if (value == null)
            {
                value = RedisCache.Get2 <T>(key);

                // 恢复本地缓存 todo 调整时间为1分钟?
                if (restoreAppCahcheSeconds != 0)
                {
                    Task.Run(async() =>
                    {
                        await Task.Delay(1);
                        if (restoreAppCahcheSeconds == -1)
                        {
                            var remainTime = RedisCache.KeyTimeToLive(key);
                            if (remainTime != null)
                            {
                                restoreAppCahcheSeconds = remainTime.Value.TotalSeconds;
                            }
                        }
                        AppCache.Set <T>(key, value, TimeSpan.FromSeconds(restoreAppCahcheSeconds));
                    });
                }
            }
            return(value);
        }
Beispiel #3
0
        private static CacheTimeRate WriteCacheByCacheTimeSetting(object resultValue, string cacheKey, double cacheSeconds, string cacheTimeSetting)
        {
            CacheTimeRate cacheTimeRate = null;

            try
            {
                if (cacheSeconds <= 0)
                {
                    return(null);
                }
                cacheTimeRate = CacheTimeSettings.GetCacheTimeRate();
                if (cacheTimeRate == null || (cacheTimeRate.AppCacheTime == 0 && cacheTimeRate.RedisCacheTime == 0))
                {
                    return(null);
                }

                // 对不需要封装的接口,无需封装
                if (!resultValue.GetType().ToString().StartsWith("Modobay.Api.ResultDto"))
                {
                    resultValue = ResultBuilder.AsSuccess(resultValue);
                }

                // 本地缓存
                if (cacheTimeRate.AppCacheTime > 0 || IsStatic(cacheTimeSetting))
                {
                    var seconds = cacheTimeRate.AppCacheTime * cacheSeconds;
                    if (seconds < 60)
                    {
                        seconds = 60;
                    }
                    if (seconds > 600)
                    {
                        seconds = 600;
                    }
                    AppCache.Set(cacheKey, resultValue, TimeSpan.FromSeconds(seconds));
                    //AppCache.Set(cacheKey, resultValue, TimeSpan.FromSeconds(cacheTimeRate.AppCacheTime * cacheSeconds));
                }

                // 分布式缓存
                if (cacheTimeRate.RedisCacheTime > 0 && !IsStatic(cacheTimeSetting)) //if (cacheTimeRate.RedisCacheTime > 0 && !RedisCache.KeyExists(cacheKey))
                {
                    RedisCache.Set2(cacheKey, resultValue, TimeSpan.FromSeconds(cacheTimeRate.RedisCacheTime * cacheSeconds));
                }

                // 静态模式更新文件?
            }
            catch (Exception ex) { Lib.Log.WriteExceptionLog($"WriteCache Exception:{cacheKey}  {ex.Message}  <br> StackTrace:{ex.StackTrace}"); }
            return(cacheTimeRate);
        }
Beispiel #4
0
        //public static void ClearDataCacheKey()
        //{
        //    var ipPort = ConfigManager.Configuration["Redis:ConnectionString"].Replace("{DataServerIP}", Modobay.AppManager.DataServerIP).Split(',')[0];
        //    var RedisCache = Modobay.Cache.CacheManager.RedisCache;
        //    var keyPrefix = $"DataCacheInvokeTask:{AppManager.ServiceAddress.Replace(':', '-')}*";
        //    var keys = RedisCache.GetServer(ipPort).Keys(0, keyPrefix, int.MaxValue);
        //    foreach (var key in keys)
        //    {
        //        RedisCache.Remove(key);
        //    }
        //}

        public static void LoadStaticCache()
        {
            var cacheKey = string.Empty;

            try
            {
                var files = Directory.GetFiles(cacheDirectory);
                foreach (var file in files)
                {
                    if (file == cacheKeyListFileName)
                    {
                        continue;
                    }
                    if (!File.Exists(file))
                    {
                        continue;
                    }

                    cacheKey = (new FileInfo(file)).Name.Replace('_', ':');
                    if (!cacheKeyList.ContainsKey(cacheKey))
                    {
                        continue;
                    }

                    // 缓存的dto必须包含在dto之中,或netcore自带的类型
                    var typeName = cacheKeyList[cacheKey];
                    var type     = Type.GetType(typeName);
                    if (type == null)
                    {
                        var asmb = Assembly.Load("Dto");
                        type = asmb.GetType(typeName);
                        if (type == null)
                        {
                            continue;
                        }
                        ;
                    }

                    var cacheResult = JsonConvert.DeserializeObject(File.ReadAllText(file), type);
                    AppCache.Set(cacheKey, cacheResult);
                }
            }
            catch (Exception ex) { Lib.Log.WriteExceptionLog($"CacheManager.LoadStaticCache:{cacheKey}:{ex.Message}  <br> StackTrace:{ex.StackTrace}"); }
        }
Beispiel #5
0
        internal static ResultDto <dynamic> ReadCache(ActionExecutingContext context, IAppContext appContext)
        {
            try
            {
                if (!IsEnableApiCache(appContext.AppID))
                {
                    return(null);
                }
                var cacheTimeRate = CacheTimeSettings.GetCacheTimeRate();
                if (cacheTimeRate == null || (cacheTimeRate.AppCacheTime == 0 && cacheTimeRate.RedisCacheTime == 0))
                {
                    return(null);
                }
                var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
                var cacheSeconds     = CalcCacheSeconds(actionDescriptor, out var cacheTimeSetting);
                if (cacheSeconds <= 0)
                {
                    return(null);
                }
                ResultDto <dynamic> cacheResult = null;
                var cacheKey = GetApiCacheKey(actionDescriptor, context.HttpContext);

                try
                {
                    if (cacheTimeRate.AppCacheTime > 0)
                    {
                        AppCache.TryGetValue <ResultDto <dynamic> >(cacheKey, out cacheResult);
                    }
                    if (cacheResult == null && cacheTimeRate.RedisCacheTime > 0)
                    {
                        cacheResult = RedisCache.Get2 <ResultDto <dynamic> >(cacheKey);

                        if (cacheResult != null && cacheTimeRate.AppCacheTime > 0)
                        {
                            // 恢复本地缓存
                            var seconds = cacheTimeRate.AppCacheTime * cacheSeconds;
                            if (seconds < 60)
                            {
                                seconds = 60;
                            }
                            if (seconds > 600)
                            {
                                seconds = 300;
                            }
                            AppCache.Set(cacheKey, cacheResult, TimeSpan.FromSeconds(seconds));
                            //AppCache.Set(cacheKey, cacheResult, TimeSpan.FromSeconds(cacheTimeRate.AppCacheTime * cacheSeconds));
                        }
                    }

                    // 存在缓存则检查缓存是否需要更新;如果cacheResult为null,则接口调用完成后由WriteCache写入缓存
                    if (cacheResult != null)
                    {
                        var isNeedUpdate = CheckUpdateAndFlag(cacheKey, cacheTimeSetting);
                        if (isNeedUpdate)
                        {
                            Task.Run(async() =>
                            {
                                var newAppContext = AppManager.CopyAppContext(appContext);
                                await Task.Delay(1);
                                var resultValue = InvokeByActionContext(context, newAppContext);
                                if (resultValue != null)
                                {
                                    WriteCacheByCacheTimeSetting(resultValue, cacheKey, cacheSeconds, cacheTimeSetting);
                                }
                            });
                        }
                    }

                    return(cacheResult);
                }
                catch (Exception ex)
                {
                    Lib.Log.WriteExceptionLog($"ReadCache-{cacheKey} Exception:{cacheKey}  {ex.Message}  <br> StackTrace:{ex.StackTrace}");
                    return(null);
                }
            }
            catch (Exception exx)
            {
                return(null);
            }
        }
Beispiel #6
0
        private static T GetAndCache <T>(Delegate func, string cacheTimeSetting, string flag = "", params object[] input)
        {
            var cacheResult = default(T);
            var cacheKey    = GetDataCacheKey <T>(func, flag);
            var cacheTime   = TimeSpan.FromSeconds(CacheTimeSettings.GetCacheSeconds(cacheTimeSetting));

            // 从本地缓存返回
            AppCache.TryGetValue(cacheKey, out cacheResult);

            // 从本地文件返回
            if (cacheResult == null && IsStatic(cacheTimeSetting))
            {
                var cacheFileName = GetCacheFileName(cacheKey);
                if (File.Exists(cacheFileName))
                {
                    cacheResult = JsonConvert.DeserializeObject <T>(File.ReadAllText(cacheFileName));
                    AppCache.Set(cacheKey, cacheResult, cacheTime);// 恢复本地缓存
                }
            }

            // 从redis缓存返回
            if (cacheResult == null && !IsStatic(cacheTimeSetting))
            {
                cacheResult = RedisCache.Get <T>(cacheKey);
                if (cacheResult != null)
                {
                    AppCache.Set(cacheKey, cacheResult, cacheTime);// 恢复本地缓存
                    //if (IsStatic(cacheTimeSetting))
                    //{
                    //    CacheFile(cacheKey, JsonConvert.SerializeObject(cacheResult), typeof(T).FullName);
                    //}
                }
            }

            // 从数据源返回
            if (cacheResult == null)
            {
                // 如果其他线程已在获取,则等待,超时再重新获取
                var isNeedUpdate = CacheManager.CheckUpdateAndFlag(cacheKey, cacheTimeSetting);//, "UpdateCache:Data"
                if (!isNeedUpdate)
                {
                    var index = 0;
                    while (cacheResult == null && index < 30)
                    {
                        index += 1;
                        AppCache.TryGetValue <T>(cacheKey, out cacheResult);
                        if (cacheResult == null)
                        {
                            cacheResult = RedisCache.Get <T>(cacheKey);
                        }
                        if (cacheResult == null)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        Lib.StopwatchLog.RecordElapsedMilliseconds($"1 {cacheKey}");
                    }
                    if (cacheResult != null)
                    {
                        return(cacheResult);
                    }
                }

                cacheResult = (T)func.DynamicInvoke(input);
                Set(cacheKey, cacheResult, cacheTime, true, IsStatic(cacheTimeSetting));
                return(cacheResult);
            }

            if (cacheTimeSetting != CacheTimeSettings.Second && CacheManager.CheckUpdateAndFlag(cacheKey, cacheTimeSetting) == true)
            {
                Task.Run(async() =>
                {
                    await Task.Delay(1);
                    cacheResult = (T)func.DynamicInvoke(input);
                    Set(cacheKey, cacheResult, cacheTime, false, IsStatic(cacheTimeSetting));
                });
            }

            // 缓存预热,每隔10分钟,先异步更新缓存,并续期,待下次访问时替换为最新缓存
            return(cacheResult);
        }