private PhoneArea GetProvinceAndCity(string mobile)
        {
            PhoneArea phoneAreaInfo = null;

//#if DEBUG
//            phoneAreaInfo = GetPhoneAreaInfo(mobile);


//#else
            if (!string.IsNullOrEmpty(mobile) && mobile.Length > 7)
            {
                try
                {
                    try
                    {
                        phoneAreaInfo = CacheProviderFactory.GetPhoneAreaCache().GetPhoneAreaByPhoneNumber(mobile);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("NOSQL读取错误。", ex);
                        phoneAreaInfo = GetPhoneAreaInfo(mobile);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("手机号段读取失败。", ex);
                }
            }
//#endif

            return(phoneAreaInfo);
        }
Exemple #2
0
        public static IApplicationBuilder UserDbRESTFul(this IApplicationBuilder app,
                                                        IApiAuthorizeFilter authorizeFilter,
                                                        bool apiOnly = false,
                                                        IResponseResultResolver responseResultResolver = null)
        {
            var loggerFactory = app.ApplicationServices.GetRequiredService <ILoggerFactory>();
            var logger        = loggerFactory.CreateLogger("DbRESTFulAPI");

            LoggerManager.Use(logger);

            var apiFilter = new ConfiguredApiFilter()
            {
                ApiAuthorizeFilter = authorizeFilter
            };

            CacheProviderFactory.Init();

            apiFilter.ResponseResultResolver = responseResultResolver == null
                ? new DefaultResponseResultResolver()
                : responseResultResolver;

            app.UseMiddleware <DbRESTFulApiMiddleware>(apiFilter, apiOnly);

            return(app);
        }
Exemple #3
0
        /// <summary>
        /// 执行调度
        /// </summary>
        /// <returns></returns>
        public ServiceRegModel DoDispatch()
        {
            regservic.CurrentContext = this.CurrentContext;
            //从注册的服务列表里面,根据服务中的长连接数量决定选取那个服务
            ServiceRegModel returnValue = null;
            ICacheProvider  cache       = CacheProviderFactory.GetGlobalCacheProvider();
            var             list        = regservic.GetActiveServerList();//已经确保GetActiveServerList 不为空
            //if (list != null)
            //{
            //    var regModel = list.Select(o => new { Count = cache.Get<int>(o.GetUri() + "_ListenerCount"), RegModel = o })
            //        .OrderBy(o => o.Count).FirstOrDefault();
            //    if (regModel != null)
            //        returnValue = regModel.RegModel;

            //}
            int minCount = int.MaxValue;

            foreach (ServiceRegModel item in list)
            {
                ServiceHostInfo host = item as ServiceHostInfo;
                if (host != null && minCount > host.ListenerCount)
                {
                    minCount    = host.ListenerCount;
                    returnValue = item;
                }
            }
            if (returnValue == null)
            {
                returnValue = this.CurrentContext.Host;
            }
            return(returnValue);
        }
        public void GetOrCreateWithslidingExpiration()
        {
            var key = Guid.NewGuid().ToString();
            var val = Guid.NewGuid();

            IHttpRuntimeCacheProvider cacheProvider = CacheProviderFactory.GetHttpRuntimeCache();
            var result = cacheProvider.GetOrCreate <Guid>(key, () => val, TimeSpan.FromSeconds(1.5D));

            Assert.AreEqual(result, val);
            {
                Thread.Sleep(1000);
                var exist = cacheProvider.TryGet <Guid>(key, out val);
                Assert.IsTrue(exist);
                Assert.AreEqual(result, val);
            }
            {
                Thread.Sleep(1000);
                var exist = cacheProvider.TryGet <Guid>(key, out val);
                Assert.IsTrue(exist);
                Assert.AreEqual(result, val);
            }
            {
                Thread.Sleep(2000);
                var exist = cacheProvider.TryGet <Guid>(key, out val);
                Assert.IsFalse(exist);
                Assert.AreEqual(val, Guid.Empty);
            }
        }
        /// <summary>
        /// Processes the put async.
        /// </summary>
        /// <returns>The put async.</returns>
        /// <param name="context">Context.</param>
        private async Task ProcessPutAsync(AspectContext context)
        {
            if (GetMethodAttributes(context.ServiceMethod).FirstOrDefault(x => x.GetType() == typeof(EasyCachingPutAttribute)) is EasyCachingPutAttribute attribute && context.ReturnValue != null)
            {
                var _cacheProvider = CacheProviderFactory.GetCachingProvider(attribute.CacheProviderName ?? Options.Value.CacheProviderName);
                var cacheKey       = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix);

                try
                {
                    if (context.IsAsync())
                    {
                        //get the result
                        var returnValue = await context.UnwrapAsyncReturnValue();

                        await _cacheProvider.SetAsync(cacheKey, returnValue, TimeSpan.FromSeconds(attribute.Expiration));
                    }
                    else
                    {
                        await _cacheProvider.SetAsync(cacheKey, context.ReturnValue, TimeSpan.FromSeconds(attribute.Expiration));
                    }
                }
                catch (Exception ex)
                {
                    if (!attribute.IsHightAvailability)
                    {
                        throw;
                    }
                    else
                    {
                        Logger?.LogError(new EventId(), ex, $"Cache provider \"{_cacheProvider.Name}\" set error.");
                    }
                }
            }
        }
Exemple #6
0
        public void WHEN_Template_Use_SubTemplate_Dependencies_SHOULD_Contains_All_TemplateNames_From_the_Tree()
        {
            //Arrange
            var controllerContext = new Mock <ControllerContext>(MockBehavior.Strict);
            var cachedView        = new HandlebarsView((w, o) => { }, GetRandom.String(32), new Dictionary <string, HandlebarsView>());

            cachedView.Dependencies.Add("SubLevel1", cachedView);
            cachedView.Dependencies.Add("SubLevel2", cachedView);
            cachedView.Dependencies.Add("OtherLeaf", cachedView);

            var cacheProvider = CacheProviderFactory.CreateForHandlebars(cachedView);
            var viewEngine    = new UnitTestableHandlebarsViewEngine(cacheProvider.Object);

            viewEngine.ViewLocationFormats        = new string[] { "~/ViewEngine/Assets/{0}.hbs" };
            viewEngine.PartialViewLocationFormats = new string[] { "~/ViewEngine/Assets/{0}.hbs" };

            //Act
            ViewEngineResult result = viewEngine.FindPartialView(controllerContext.Object, "Root", false);

            //Assert
            result.View.Should().BeOfType <HandlebarsView>();
            result.View.As <HandlebarsView>().CompiledTemplate.Should().NotBeNull();
            result.View.As <HandlebarsView>().VirtualPath.Should().NotBeNull();
            result.View.As <HandlebarsView>().Dependencies.Should().ContainKey("SubLevel1");
            result.View.As <HandlebarsView>().Dependencies.Should().ContainKey("SubLevel2");
            result.View.As <HandlebarsView>().Dependencies.Should().ContainKey("OtherLeaf");
        }
Exemple #7
0
        public void ExpireAll()
        {
            var key = Guid.NewGuid().ToString();
            //region a 创建 key->val1
            IHttpRuntimeCacheProvider cacheProvider1 = CacheProviderFactory.GetHttpRuntimeCache("e");

            cacheProvider1.GetOrCreate <Guid>(key, k => Guid.NewGuid());

            //reigon b 创建 key-val2
            IHttpRuntimeCacheProvider cacheProvider2 = CacheProviderFactory.GetHttpRuntimeCache("f");

            cacheProvider2.GetOrCreate <Guid>(key, k => Guid.NewGuid());

            //region a 过期全部, 确认 region b 未被过期
            ((HttpRuntimeCacheProvider)cacheProvider1).ExpireAll();
            Guid val1;
            var  exist = cacheProvider1.TryGet <Guid>(key, out val1);

            Assert.IsFalse(exist);
            Assert.AreEqual(val1, Guid.Empty);

            Guid val2;
            var  exist2 = cacheProvider2.TryGet <Guid>(key, out val2);

            Assert.IsTrue(exist2);
        }
Exemple #8
0
        public void Duplicate2()
        {
            var key = Guid.NewGuid().ToString();
            //region a 创建 key->val1
            IHttpRuntimeCacheProvider cacheProvider1 = CacheProviderFactory.GetHttpRuntimeCache("c");

            cacheProvider1.GetOrCreate <Guid>(key, k => Guid.NewGuid());
            Assert.IsTrue(((HttpRuntimeCacheProvider)cacheProvider1).Count() == 1);

            //reigon b 创建 key-val2
            IHttpRuntimeCacheProvider cacheProvider2 = CacheProviderFactory.GetHttpRuntimeCache("d");

            cacheProvider2.GetOrCreate <Guid>(key, k => Guid.NewGuid());
            Assert.IsTrue(((HttpRuntimeCacheProvider)cacheProvider2).Count() == 1);


            //确认reigon a 键 key 与 region b 键 key 对应值不同
            Guid val1;
            var  exist1 = cacheProvider1.TryGet <Guid>(key, out val1);

            Assert.IsTrue(exist1);

            Guid val2;
            var  exist2 = cacheProvider2.TryGet <Guid>(key, out val2);

            Assert.IsTrue(exist2);

            Assert.AreNotEqual(val1, val2);
        }
        /// <summary>
        /// Processes the evict async.
        /// </summary>
        /// <returns>The evict async.</returns>
        /// <param name="context">Context.</param>
        /// <param name="isBefore">If set to <c>true</c> is before.</param>
        private async Task ProcessEvictAsync(AspectContext context, bool isBefore)
        {
            if (GetMethodAttributes(context.ServiceMethod).FirstOrDefault(x => x.GetType() == typeof(EasyCachingEvictAttribute)) is EasyCachingEvictAttribute attribute && attribute.IsBefore == isBefore)
            {
                var _cacheProvider = CacheProviderFactory.GetCachingProvider(attribute.CacheProviderName ?? Options.Value.CacheProviderName);
                try
                {
                    if (attribute.IsAll)
                    {
                        //If is all , clear all cached items which cachekey start with the prefix.
                        var cachePrefix = KeyGenerator.GetCacheKeyPrefix(context.ServiceMethod, attribute.CacheKeyPrefix);

                        await _cacheProvider.RemoveByPrefixAsync(cachePrefix);
                    }
                    else
                    {
                        //If not all , just remove the cached item by its cachekey.
                        var cacheKey = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix);

                        await _cacheProvider.RemoveAsync(cacheKey);
                    }
                }
                catch (Exception ex)
                {
                    if (!attribute.IsHightAvailability)
                    {
                        throw;
                    }
                    else
                    {
                        Logger?.LogError(new EventId(), ex, $"Cache provider \"{_cacheProvider.Name}\" remove error.");
                    }
                }
            }
        }
        private object ExcuteApi(ConfiguredAPI api, HttpContext context, JToken param)
        {
            if (!api.implemented)
            {
                if (api.mock == null)
                {
                    throw new Exception("No mock data configured.");
                }

                var data = ResolveMock(param, api.mock);
                return(data);
            }

            var identity = ApiAuthorizeFilter.OnAuthorization(context, api.allowAnonymous);

            context.Items.Add("identity", identity);

            var cacheKey = context.Request.Path + (context.Request.QueryString.HasValue ? context.Request.QueryString.Value : "");

            if (api.cache?.enabled == true)
            {
                var data = CacheProviderFactory.Get(api.cache.type, cacheKey);

                if (data != null)
                {
                    return(SetStandardResult(context, data));
                }
            }

            object result;

            if (api.implementation.type == "csi")
            {
                DbRESTFulRepository repository = new DbRESTFulRepository()
                {
                    HttpContext = context, CurrentUser = identity
                };
                result = repository.Invoke(api.implementation.name, param);
            }
            else if (api.implementation.type == "repository")
            {
                result = RepositoryInvoker.Call(api.implementation.name, param, identity, context);
            }
            else if (api.implementation.type == "cri")
            {
                result = RedisInvoker.Call(api.implementation.name, param);
            }
            else
            {
                throw new Exception(string.Format("Unsupported implementation type '{0}'", api.implementation.type));
            }

            if (api.cache?.enabled == true)
            {
                CacheProviderFactory.Set(api.cache.type, cacheKey, result, api.cache.expiration);
            }

            return(SetStandardResult(context, result));
        }
        public void SetUp()
        {
            _container = new AutoMocker();
            _container.Use(CacheProviderFactory.CreateForLocalizationTree());
            _container.Use(ComposerEnvironmentFactory.Create());

            _localizationProvider = _container.CreateInstance <ResourceLocalizationProvider>();
        }
        public static ICacheProvider GetProvider()
        {
            if (instance == null)
            {
                instance = CacheProviderFactory.Create();
            }

            return(instance);
        }
Exemple #13
0
 internal PipelineExecutionContext(IWorkflowExecutionContext workflowExecutionContext, OrationiDatabaseContext dbContext)
 {
     PipelineValues            = new Dictionary <string, object>();
     PluginStepSettings        = new Dictionary <string, object>();
     _workflowExecutionContext = workflowExecutionContext;
     _fileStores   = dbContext.FileStores;
     CacheProvider = CacheProviderFactory.Create(dbContext);
     RequestBody   = _workflowExecutionContext.MessageBody;
 }
        public void TryGet()
        {
            var  key = Guid.NewGuid().ToString();
            Guid val;

            IHttpRuntimeCacheProvider cacheProvider = CacheProviderFactory.GetHttpRuntimeCache();
            var exist = cacheProvider.TryGet <Guid>(key, out val);

            Assert.IsFalse(exist);
            Assert.AreEqual(val, Guid.Empty);
        }
Exemple #15
0
        /// <summary>
        /// Invoke the specified context and next.
        /// </summary>
        /// <returns>The invoke.</returns>
        /// <param name="context">Context.</param>
        /// <param name="next">Next.</param>
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            _cacheProvider = _cacheProvider ?? CacheProviderFactory.GetCachingProvider(Options.Value.CacheProviderName);
            //Process any early evictions
            await ProcessEvictAsync(context, true);

            //Process any cache interceptor
            await ProceedAbleAsync(context, next);

            // Process any put requests
            await ProcessPutAsync(context);

            // Process any late evictions
            await ProcessEvictAsync(context, false);
        }
Exemple #16
0
        public void ReferenceTypeValueChangeToNull()
        {
            var            key   = "key-object-null";
            ICacheProvider cache = CacheProviderFactory.GetHttpContextCache();
            var            id1   = new Object();
            var            id2   = cache.GetOrCreate(key, () => id1);

            Assert.AreEqual(id1, id2);

            id1 = null;
            Object id3;
            var    exist = cache.TryGet(key, out id3);

            Assert.IsTrue(exist);
            Assert.AreEqual(id2, id3);
        }
        private void Start(IConsulClient consulClient, ILoggerFactory logerFactory)
        {
            if (ServiceInfo != null)
            {
                var configFilePath = Path.Combine(ServiceInfo.Location, "config.json");
                ConfigurationManager.Setup(configFilePath, logerFactory);
                ServiceResourceManager.Load();
                CacheProviderFactory.Init();

                var lifetime = GetMicroserviceLifetime();
                lifetime?.Start();

                ServiceInfo.StartedAt = DateTime.Now;
            }

            consulClient.RegisterMicroServiceAsync(ServiceInfo);
        }
Exemple #18
0
        public void ValueType()
        {
            var            key   = "key-guid";
            ICacheProvider cache = CacheProviderFactory.GetHttpContextCache();
            var            id1   = Guid.NewGuid();
            var            id2   = cache.GetOrCreate(key, () => id1);

            Assert.AreEqual(id1, id2);

            cache.Expire(key);
            Guid id3;
            var  exist = cache.TryGet(key, out id3);

            Assert.IsFalse(exist);
            Assert.AreNotEqual(id1, id3);
            Assert.AreEqual(id3, Guid.Empty);
        }
Exemple #19
0
        public void ReferenceType()
        {
            var            key   = "key-object";
            ICacheProvider cache = CacheProviderFactory.GetHttpContextCache();
            var            id1   = new Object();
            var            id2   = cache.GetOrCreate(key, () => id1);

            Assert.AreEqual(id1, id2);

            cache.Expire(key);
            Object id3;
            var    exist = cache.TryGet(key, out id3);

            Assert.IsFalse(exist);
            Assert.AreNotEqual(id1, id3);
            Assert.AreEqual(id3, null);
        }
        public void Expire()
        {
            var key = Guid.NewGuid().ToString();
            var val = Guid.NewGuid();

            IHttpRuntimeCacheProvider cacheProvider = CacheProviderFactory.GetHttpRuntimeCache();
            var result = cacheProvider.GetOrCreate <Guid>(key, () => val);

            Assert.AreEqual(result, val);

            cacheProvider.Expire(key);
            Guid val2;
            var  exist = cacheProvider.TryGet <Guid>(key, out val2);

            Assert.IsFalse(exist);
            Assert.AreEqual(val2, Guid.Empty);
        }
        public async Task WHEN_Passing_Any_Culture_Resulting_TreeStructure_SHOULD_Be_Cached_ByCulture()
        {
            //Arrange
            CacheProviderFactory.CacheHistMonitor monitor = new CacheProviderFactory.CacheHistMonitor();
            LocalizationTree cachedTree = new LocalizationTree(CultureInfo.CurrentCulture);

            AutoMocker container = new AutoMocker();

            container.Use(CacheProviderFactory.CreateWithMonitor(monitor, cachedTree));
            container.Use(ComposerEnvironmentFactory.Create());

            ILocalizationProvider localizationProvider = container.CreateInstance <ResourceLocalizationProvider>();

            CultureInfo cultureA = CultureInfo.GetCultureInfo("fr-CA");
            CultureInfo cultureB = CultureInfo.GetCultureInfo("fr-FR");

            //Act
            monitor.Reset();
            monitor.CacheMissCount.ShouldBeEquivalentTo(0, "Otherwise this test is irrelevent");
            monitor.CacheHitCount.ShouldBeEquivalentTo(0, "Otherwise this test is irrelevent");

            LocalizationTree tree1A = await localizationProvider.GetLocalizationTreeAsync(cultureA);

            monitor.CacheMissCount.ShouldBeEquivalentTo(1, "First attempt to load the CultureA should cache miss");

            LocalizationTree tree2A = await localizationProvider.GetLocalizationTreeAsync(cultureA);

            monitor.CacheHitCount.ShouldBeEquivalentTo(1, "Second attempt to load the CultureA should cache hit");

            monitor.Reset();
            for (int i = 0; i < 10; i++)
            {
                LocalizationTree tree3A = await localizationProvider.GetLocalizationTreeAsync(cultureA);
            }
            monitor.CacheMissCount.ShouldBeEquivalentTo(0, "Subsequent attempt to load the CultureA should not cache miss");
            monitor.CacheHitCount.Should().BeGreaterOrEqualTo(10, "Subsequent attempt to load the CultureA should cache hit");

            //--
            monitor.Reset();
            LocalizationTree tree1B = await localizationProvider.GetLocalizationTreeAsync(cultureB);

            monitor.CacheMissCount.ShouldBeEquivalentTo(1, "First attempt to load the CultureB should cache miss, key is culture dependant");
            monitor.CacheHitCount.ShouldBeEquivalentTo(0, "First attempt to load the CultureB should not cache hit, key is culture dependant");
        }
        public void Overwrite()
        {
            var key = Guid.NewGuid().ToString();
            var val = Guid.NewGuid();

            IHttpRuntimeCacheProvider cacheProvider = CacheProviderFactory.GetHttpRuntimeCache();
            var result = cacheProvider.GetOrCreate <Guid>(key, () => val);

            Assert.AreEqual(result, val);

            var val2 = Guid.NewGuid();

            cacheProvider.Overwrite <Guid>(key, val2);

            Guid val3;
            var  exist = cacheProvider.TryGet <Guid>(key, out val3);

            Assert.IsTrue(exist);
            Assert.AreEqual(val3, val2);
        }
        public void GetOrCreateWithAbsoluteExpiration()
        {
            var key = Guid.NewGuid().ToString();
            var val = Guid.NewGuid();

            IHttpRuntimeCacheProvider cacheProvider = CacheProviderFactory.GetHttpRuntimeCache();
            var result = cacheProvider.GetOrCreate <Guid>(key, () => val, DateTime.UtcNow.AddSeconds(2D));

            Assert.AreEqual(result, val);

            var exist = cacheProvider.TryGet <Guid>(key, out val);

            Assert.IsTrue(exist);
            Assert.AreEqual(result, val);

            Thread.Sleep(2000);
            exist = cacheProvider.TryGet <Guid>(key, out val);
            Assert.IsFalse(exist);
            Assert.AreEqual(val, Guid.Empty);
        }
Exemple #24
0
        public void WHEN_Passing_Any_TemplateName_Resulting_View_SHOULD_Be_Cached_ByTemplateName()
        {
            //Arrange
            var controllerContext = new Mock <ControllerContext>(MockBehavior.Strict);
            var cachedView        = new HandlebarsView((w, o) => { }, GetRandom.String(32), new Dictionary <string, HandlebarsView>());
            var monitor           = new CacheProviderFactory.CacheHistMonitor();
            var cacheProvider     = CacheProviderFactory.CreateForHandlebarsWithMonitor(monitor, cachedView, cachedView);
            var viewEngine        = new UnitTestableHandlebarsViewEngine(cacheProvider.Object);

            string templateNameA = "SubLevel2";
            string templateNameB = "OtherLeaf";

            //Act
            monitor.Reset();
            monitor.CacheMissCount.ShouldBeEquivalentTo(0, "Otherwise this test is irrelevent");
            monitor.CacheHitCount.ShouldBeEquivalentTo(0, "Otherwise this test is irrelevent");

            var result1A = viewEngine.FindPartialView(controllerContext.Object, templateNameA, false);

            monitor.CacheMissCount.ShouldBeEquivalentTo(1, "First attempt to load the TemplateA should cache miss");

            var result2A = viewEngine.FindPartialView(controllerContext.Object, templateNameA, false);

            monitor.CacheHitCount.ShouldBeEquivalentTo(1, "Second attempt to load the TemplateA should cache hit");

            monitor.Reset();
            for (int i = 0; i < 10; i++)
            {
                var result3A = viewEngine.FindPartialView(controllerContext.Object, templateNameA, false);
            }
            monitor.CacheMissCount.ShouldBeEquivalentTo(0, "Subsequent attempt to load the TemplateA should not cache miss");
            monitor.CacheHitCount.Should().BeGreaterOrEqualTo(10, "Subsequent attempt to load the TemplateA should cache hit");

            //--
            monitor.Reset();
            var result1B = viewEngine.FindPartialView(controllerContext.Object, templateNameB, false);

            monitor.CacheMissCount.ShouldBeEquivalentTo(1, "First attempt to load the CultureB should cache miss, key is culture dependant");
            monitor.CacheHitCount.ShouldBeEquivalentTo(0, "First attempt to load the CultureB should not cache hit, key is culture dependant");
        }
Exemple #25
0
        public void Concurrency()
        {
            HttpRuntimeCacheProvider cacheProvider1 = (HttpRuntimeCacheProvider)CacheProviderFactory.GetHttpRuntimeCache("g");
            HttpRuntimeCacheProvider cacheProvider2 = (HttpRuntimeCacheProvider)CacheProviderFactory.GetHttpRuntimeCache("h");

            var tasks = new List <Task>();

            for (int i = 0; i < 100; i++)
            {
                if ((Guid.NewGuid().GetHashCode() & 1) == 0)
                {
                    tasks.Add(new Task(action: x => cacheProvider1.GetOrCreate(x.ToString(), k => x), state: i));
                }
                else
                {
                    tasks.Add(new Task(action: x => cacheProvider2.GetOrCreate(x.ToString(), k => x), state: i));
                }
            }
            foreach (var task in tasks)
            {
                task.Start();
            }
            Task.WaitAll(tasks.ToArray(), CancellationToken.None);

            var count1 = cacheProvider1.Count();
            var count2 = cacheProvider2.Count();

            cacheProvider1.ExpireAll();
            Assert.IsTrue(cacheProvider1.Count() == 0);
            Assert.IsTrue(cacheProvider2.Count() == count2);

            foreach (var entry in System.Web.HttpRuntime.Cache.OfType <DictionaryEntry>())
            {
                Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
            }
        }
        public void GetOrCreate()
        {
            var key = Guid.NewGuid().ToString();
            var val = Guid.NewGuid();

            IHttpRuntimeCacheProvider cacheProvider = CacheProviderFactory.GetHttpRuntimeCache();
            var result = cacheProvider.GetOrCreate <Guid>(key, () => val);

            Assert.AreEqual(result, val);

            {
                var exist = cacheProvider.TryGet <Guid>(key, out val);
                Assert.IsTrue(exist);
                Assert.AreEqual(result, val);
            }

            {
                var result2 = cacheProvider.GetOrCreate <Guid>(key, () => {
                    Assert.Fail();
                    return(Guid.NewGuid());
                });
                Assert.AreEqual(result2, val);
            }
        }
Exemple #27
0
        /// <summary>
        /// 监听器统计,如果服务挂机,则统计信息在1分钟后过期
        /// </summary>
        private static void ListenersCountTimer()
        {
            CountTimer = new System.Threading.Timer(new System.Threading.TimerCallback(o =>
            {
                DateTime dt    = DateTime.Now;
                int[] arrCount = MessageCenter.Instance.CheckListeners();
                int currCount  = arrCount[0];
                //将监听器数量写入全局缓存,供集群调度服务使用
                ICacheProvider cache = CacheProviderFactory.GetGlobalCacheProvider();
                string key           = Program.Host.GetUri() + "_HostInfo";

                ServiceHostInfo serviceHostInfo = cache.Get <ServiceHostInfo>(key, () =>
                {
                    ServiceHostInfo info     = new ServiceHostInfo();
                    info.RegServerDesc       = Program.Host.RegServerDesc;
                    info.RegServerIP         = Program.Host.RegServerIP;
                    info.RegServerPort       = Program.Host.RegServerPort;
                    info.IsActive            = Program.Host.IsActive;
                    info.ServerMappingIP     = Program.Host.ServerMappingIP;
                    info.LogDirectory        = Program.Host.LogDirectory;
                    info.ListenerCount       = currCount;
                    info.ListenerMaxCount    = currCount;
                    info.ListenerMaxDateTime = DateTime.Now;
                    info.ActiveConnectCount  = arrCount[1];
                    return(info);
                },
                                                                              new System.Runtime.Caching.CacheItemPolicy()
                {
                    SlidingExpiration = new TimeSpan(0, 10, 0)
                }
                                                                              );

                bool changed = false;
                int maxCount = serviceHostInfo.ListenerMaxCount;

                if (currCount > maxCount)
                {
                    changed  = true;
                    maxCount = currCount;
                    serviceHostInfo.ListenerCount       = currCount;
                    serviceHostInfo.ListenerMaxCount    = maxCount;
                    serviceHostInfo.ListenerMaxDateTime = DateTime.Now;
                }
                else if (currCount != serviceHostInfo.ListenerCount)
                {
                    changed = true;
                    serviceHostInfo.ListenerCount = currCount;
                }

                if (changed)
                {
                    serviceHostInfo.ActiveConnectCount = arrCount[1];

                    Host.ListenerCount       = serviceHostInfo.ListenerCount;
                    Host.ListenerMaxCount    = serviceHostInfo.ListenerMaxCount;
                    Host.ListenerMaxDateTime = serviceHostInfo.ListenerMaxDateTime;
                    Host.ActiveConnectCount  = serviceHostInfo.ActiveConnectCount;

                    cache.Insert <ServiceHostInfo>(
                        key,
                        serviceHostInfo,
                        new System.Runtime.Caching.CacheItemPolicy()
                    {
                        SlidingExpiration = new TimeSpan(0, 1, 0)
                    }
                        );
                }
                Console.WriteLine("=========监听器数量统计:当前{0}个,最大{1}个,用时{2} ms ============", currCount, maxCount, DateTime.Now.Subtract(dt).TotalMilliseconds);
            }), null, 1000, 10000);
        }
 public MemoryCacheService()
 {
     Provider = CacheProviderFactory.GetInMemoryCacheProvider(this);
 }
Exemple #29
0
        /// <summary>
        /// Proceeds the able async.
        /// </summary>
        /// <returns>The able async.</returns>
        /// <param name="context">Context.</param>
        /// <param name="next">Next.</param>
        private async Task ProceedAbleAsync(AspectContext context, AspectDelegate next)
        {
            if (GetMethodAttributes(context.ServiceMethod).FirstOrDefault(x => typeof(EasyCachingAbleAttribute).IsAssignableFrom(x.GetType())) is EasyCachingAbleAttribute attribute)
            {
                var returnType = context.IsAsync()
                        ? context.ServiceMethod.ReturnType.GetGenericArguments().First()
                        : context.ServiceMethod.ReturnType;

                var cacheKey = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix);

                object cacheValue  = null;
                var    isAvailable = true;
                try
                {
                    if (attribute.IsHybridProvider)
                    {
                        cacheValue = await HybridCachingProvider.GetAsync(cacheKey, returnType);
                    }
                    else
                    {
                        var _cacheProvider = CacheProviderFactory.GetCachingProvider(attribute.CacheProviderName ?? Options.Value.CacheProviderName);
                        cacheValue = await _cacheProvider.GetAsync(cacheKey, returnType);
                    }
                }
                catch (Exception ex)
                {
                    if (!attribute.IsHighAvailability)
                    {
                        throw;
                    }
                    else
                    {
                        isAvailable = false;
                        Logger?.LogError(new EventId(), ex, $"Cache provider get error.");
                    }
                }

                if (cacheValue != null)
                {
                    if (context.IsAsync())
                    {
                        //#1
                        //dynamic member = context.ServiceMethod.ReturnType.GetMember("Result")[0];
                        //dynamic temp = System.Convert.ChangeType(cacheValue.Value, member.PropertyType);
                        //context.ReturnValue = System.Convert.ChangeType(Task.FromResult(temp), context.ServiceMethod.ReturnType);

                        //#2
                        context.ReturnValue =
                            TypeofTaskResultMethod.GetOrAdd(returnType, t => typeof(Task).GetMethods().First(p => p.Name == "FromResult" && p.ContainsGenericParameters).MakeGenericMethod(returnType)).Invoke(null, new object[] { cacheValue });
                    }
                    else
                    {
                        //context.ReturnValue = System.Convert.ChangeType(cacheValue.Value, context.ServiceMethod.ReturnType);
                        context.ReturnValue = cacheValue;
                    }
                }
                else
                {
                    // Invoke the method if we don't have a cache hit
                    await next(context);

                    if (isAvailable)
                    {
                        // get the result
                        var returnValue = context.IsAsync()
                            ? await context.UnwrapAsyncReturnValue()
                            : context.ReturnValue;

                        // should we do something when method return null?
                        // 1. cached a null value for a short time
                        // 2. do nothing
                        if (returnValue != null)
                        {
                            if (attribute.IsHybridProvider)
                            {
                                await HybridCachingProvider.SetAsync(cacheKey, returnValue, TimeSpan.FromSeconds(attribute.Expiration));
                            }
                            else
                            {
                                var _cacheProvider = CacheProviderFactory.GetCachingProvider(attribute.CacheProviderName ?? Options.Value.CacheProviderName);
                                await _cacheProvider.SetAsync(cacheKey, returnValue, TimeSpan.FromSeconds(attribute.Expiration));
                            }
                        }
                    }
                }
            }
            else
            {
                // Invoke the method if we don't have EasyCachingAbleAttribute
                await next(context);
            }
        }
Exemple #30
0
 public RedisCacheService(RedisConfig cfg)
 {
     Provider = CacheProviderFactory.GetRedisCacheProvider(this, cfg);
 }