/// <summary> /// 尝试获取指定表达式的缓存。 /// </summary> /// <param name="expression"></param> /// <param name="context"></param> /// <param name="creator">当缓存不存在时,创建缓存数据的函数。</param> /// <returns></returns> Delegate IQueryCache.TryGetDelegate(Expression expression, QueryCacheContext context, Func <LambdaExpression> creator) { var section = ConfigurationUnity.GetSection <TranslatorConfigurationSection>(); var option = section == null ? TranslateOptions.Default : section.Options; var result = CacheableChecker.Check(expression); if (!result.Required || (result.Enabled == null && (context.Enabled == false || (context.Enabled == null && !option.CacheParsing))) || result.Enabled == false) { return(creator().Compile()); } var generator = _serviceProvider.TryGetService <IQueryCacheKeyGenerator>(() => ExpressionKeyGenerator.Instance); var cacheKey = _serviceProvider.GetCacheKey(generator.Generate(expression, "Trans")); Tracer.Debug($"QueryCache access to '{cacheKey}'"); var cacheMgr = _serviceProvider.TryGetService <IMemoryCacheManager>(() => MemoryCacheManager.Instance); return(cacheMgr.TryGet(cacheKey, () => { var lambdaExp = creator() as LambdaExpression; var segment = SegmentFinder.Find(expression); if (segment != null) { //将表达式内的 Segment 替换成参数 var segParExp = Expression.Parameter(typeof(IDataSegment), "g"); var newExp = SegmentReplacer.Repalce(lambdaExp.Body, segParExp); var parameters = new List <ParameterExpression>(lambdaExp.Parameters); parameters.Insert(1, segParExp); lambdaExp = Expression.Lambda(newExp, parameters.ToArray()); } return lambdaExp.Compile(); }, () => new RelativeTime(GetExpire(result, option, context)))); }
private TimeSpan GetExpire(CacheableCheckResult result, TranslateOptions option, QueryCacheContext cacheOpt) { if (result.Expired != null) { return(result.Expired.Value); } else if (cacheOpt.Times != null) { return(cacheOpt.Times.Value); } return(option.CacheExecutionTimes); }