public RedisCacheProvider(CacheOption cacheOption) { var redisClient = new CSRedisClient( $"{cacheOption.IpAddress},password={cacheOption.Password},defaultDatabase={cacheOption.DefaultDatabase},poolsize={cacheOption.PoolSize},ssl=false,writeBuffer={cacheOption.WriteBuffer},prefix={cacheOption.Prefix}"); RedisHelper.Initialization(redisClient); }
public void CanDisableCaching() { var cacheOption = new CacheOption(); Assert.That(cacheOption.CacheReport, Is.False, "CacheReport"); Assert.That(cacheOption.ExpirationMinutes, Is.Null, "ExpirationMinutes"); }
public void ShouldSetExpireInSeconds() { var expectedExpiresInSecond = 1; var option = new CacheOption(expireInSeconds: expectedExpiresInSecond); Assert.Equal(expectedExpiresInSecond, option.ExpireInSeconds); }
public Result SendVerificationCode(string account, string email) { Result Result = new Result(); try { Random random = new Random(); if (UserService.GetUser(account) != null) { throw new Exception("该账号已经被注册!"); } string code = random.Next(0, 9).ToString() + random.Next(0, 9).ToString() + random.Next(0, 9).ToString() + random.Next(0, 9).ToString(); CacheOption.SetValue("register_{0}".ToFormat(account), code, DateTime.Now + TimeSpan.FromHours(1)); EmailConnect.SendEmail("火星人脚本账号注册", "验证码:{0}".ToFormat(code), email); Result.Data = "已经成功发送验证码,验证码只有一小时的有效期!"; } catch (Exception ex) { Result.Msg = ex.Message; Result.SetCode(ResultCode.Fail); } return(Result); }
public void Success() { var provider = new QueryInfoProvider(new List <Type> { typeof(FooQueryHandler), typeof(BarQueryHandler) }); var fooQueryInfo = provider.GetQueryInfo(typeof(FooQuery).Name); var fooQueryCacheAttribute = typeof(FooQueryHandler).GetCustomAttribute <DecorateRedisCacheAttribute>(); var fooCacheOption = new CacheOption(fooQueryCacheAttribute.ExpireInSeconds, fooQueryCacheAttribute.CacheKeyProviderType); Assert.NotNull(fooQueryInfo); Assert.Equal(typeof(FooQueryHandler), fooQueryInfo.HandlerType); Assert.Equal(typeof(FooQuery).Name, fooQueryInfo.Name); Assert.True(fooQueryInfo.HasCache); Assert.Equal(fooCacheOption, fooQueryInfo.CacheOption); var barQueryInfo = provider.GetQueryInfo(typeof(BarQuery).Name); Assert.NotNull(barQueryInfo); Assert.Equal(typeof(BarQueryHandler), barQueryInfo.HandlerType); Assert.Equal(typeof(BarQuery).Name, barQueryInfo.Name); Assert.False(barQueryInfo.HasCache); Assert.Null(barQueryInfo.CacheOption); }
public void ShouldSetCacheKeyProviderType() { var expectedCacheKeyProviderType = typeof(FooCacheKeyProvider); var option = new CacheOption(cacheKeyProviderType: expectedCacheKeyProviderType); Assert.Equal(expectedCacheKeyProviderType, option.CacheKeyProviderType); }
public void CanSpecifyCacheDurationInMinutes() { const int CACHE_MINUTES = 20; var cacheOption = new CacheOption(CACHE_MINUTES); Assert.That(cacheOption.CacheReport, Is.True, "CacheReport"); Assert.That(cacheOption.ExpirationMinutes, Is.EqualTo(CACHE_MINUTES), "ExpirationMinutes"); }
public static CacheOption CreateCacheOption(string redisConnector) { var option = new CacheOption(); option.CacheType = CacheType.DistributedMemoryCache; option.Params.Add(_redisConnectorKey, redisConnector); return(option); }
public void ShouldSetDefaultValues() { var expectedExpiresInSecond = default(double); var expectedCacheKeyProviderType = default(Type); var option = new CacheOption(); Assert.Equal(expectedExpiresInSecond, option.ExpireInSeconds); Assert.Equal(expectedCacheKeyProviderType, option.CacheKeyProviderType); }
//fetch json 到本地 public static void sign_UpdateTable(string api, string db_path, bool is_append) { var cache = new CacheOption <T>(); print("v1/app/xml :" + api); print(db_path); // cache.setCache_dbPath(PublicClass.server_ip + "v1/app/xml/getTempSignNew",db_path); cache.setCache_dbPath(api, db_path, is_append); print("getTempSignNew success"); }
public ApiGatewayConfig() { Balancer.Add(new BalancerOption { Enable = false, Host = "localhost:64516", Nodes = new Node[] { new Node { Host = "google.com", Port = 443, Scheme = "https", Enable = true }, new Node { Host = "amazon.com", Port = 443, Scheme = "https", Enable = true } }, Path = "^(.*)$", Policy = "RoundRobin", Port = 64516, Scheme = "http" }); Proxy.Add(new ProxyOption { Enable = false, Host = "localhost:64516", Node = new Node { Host = "google.com", Port = 443, Scheme = "https" }, Path = "^(.*)$", Port = 64516, Scheme = "http" }); Cache = new CacheOption { Enable = false, Duration = 600, MaximumBodySize = 100 * 1024 * 1024, SizeLimit = 64 * 1024 * 1024, UseCaseSensitivePaths = false }; Logging = new LoggingOption { Enable = false }; }
public IEnumerator GetData() { var cache_resWeb = new CacheOption <GetResWeb>(); cache_resWeb.setCacheJson("http://res.vesal.site/json/V310_GetResWeb.json"); yield return(null); var cache_resRelation = new CacheOption <GetResRelation>(); cache_resRelation.setCacheJson("http://res.vesal.site/json/V310_GetResRelation.json"); yield return(null); }
/// <summary> /// /// </summary> /// <param name="attribute"></param> /// <returns></returns> public static CacheOption GetCacheOption(this CacheAttribute attribute) { var option = new CacheOption { Enabled = attribute.Enabled, }; if (attribute.ExpireIn != null) { option.ExpireIn = attribute.ExpireIn; } return(option); }
public void EqualTest() { object nullObject = null; var cacheKeyProvider = typeof(FooCacheKeyProvider); var option1 = new CacheOption(1, cacheKeyProvider); var option2 = new CacheOption(2, cacheKeyProvider); var option1_2 = new CacheOption(1, cacheKeyProvider); Assert.False(option1.Equals(option2)); Assert.False(option1.Equals(null)); Assert.False(option1.Equals(nullObject)); Assert.True(option1.Equals(option1_2)); }
public DistributedMemoryCache(CacheOption option) { string redisConnector = option?.Params?[_redisConnectorKey]?.ToString(); if (string.IsNullOrEmpty(redisConnector)) { throw new ArgumentNullException(_redisConnectorKey); } //创建连接 _redis = RedisConnector.Open(redisConnector); _subscriber = _redis.GetSubscriber(); //订阅CacheRunner的通道 _subscriber.Subscribe(_channel, Broker_MsgRecevied); CacheSyncMsgDispatcher.Initialize(redisConnector, _self); }
public Result Register(string account, string password, string code, string email, string recommend) { Result obj = new Result(); try { string value = CacheOption.GetValue <string>("register_{0}".ToFormat(account)); if (string.IsNullOrEmpty(value)) { throw new Exception("该账号没有被发送过邮箱验证,请在发送邮箱验证之后不要" + "更改填写的账号!"); } if (!value.Equals(code)) { throw new Exception("验证码错误,请检查发送到指定邮箱的验证码!"); } User user = new User() { Name = account, Password = MD5Comm.Get32MD5One(password), Email = email, Level = 0, CreateTime = DateTime.Now, }; obj.SetCode(UserService.AddUser(user) ? ResultCode.Success : ResultCode.Fail); try { UserService.ActiveAccount(user.Name, recommend, true); } catch (Exception) { } } catch (Exception ex) { obj.Msg = ex.Message; obj.SetCode(ResultCode.Fail); } return(obj); }
public void Success() { // var provider = new QueryInfoProvider(new List<Type> // { // typeof(FooQueryHandler), // typeof(BarQueryHandler) // }); var builder = new ServiceCollection(); builder.AddQuantic(opt => { opt.Assemblies = new System.Reflection.Assembly[] { typeof(FooQueryHandler).Assembly }; }).AddMemoryCacheDecorator(opt => { }); var container = builder.BuildServiceProvider(); var provider = container.GetService <IQueryInfoProvider>(); var fooQueryInfo = provider.GetQueryInfo(typeof(FooQuery).Name); var fooQueryCacheAttribute = typeof(FooQueryHandler).GetCustomAttribute <DecorateInMemoryCacheAttribute>(); var fooCacheOption = new CacheOption(fooQueryCacheAttribute.ExpireInSeconds, fooQueryCacheAttribute.CacheKeyProviderType); Assert.NotNull(fooQueryInfo); Assert.Equal(typeof(FooQueryHandler), fooQueryInfo.HandlerType); Assert.Equal(typeof(FooQuery).Name, fooQueryInfo.Name); Assert.True(fooQueryInfo.HasCache); Assert.Equal(fooCacheOption, fooQueryInfo.CacheOption); var barQueryInfo = provider.GetQueryInfo(typeof(BarQuery).Name); Assert.NotNull(barQueryInfo); Assert.Equal(typeof(BarQueryHandler), barQueryInfo.HandlerType); Assert.Equal(typeof(BarQuery).Name, barQueryInfo.Name); Assert.False(barQueryInfo.HasCache); Assert.Null(barQueryInfo.CacheOption); }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <param name="option"></param> public void Write(HttpResponse response, CacheOption option) { if (option == null || !option.Enabled || !option.CanCached(response)) { return; } var cacheOption = new MemoryCacheEntryOptions(); var type = option.ExpireType ?? ExpireType.Absolute; switch (type) { case ExpireType.Absolute: cacheOption.AbsoluteExpirationRelativeToNow = option.ExpireIn; break; case ExpireType.Sliding: cacheOption.SlidingExpiration = option.ExpireIn; break; } _caching.Set <HttpResponse>(response.RequestHashValue, response, cacheOption); }
/// <summary> /// necessary for using LeagueOfLegendsApi /// </summary> /// <param name="services"> /// </param> /// <param name="riotApiKey"> /// RiotGames DeveloperKey or ProductionKey /// </param> /// <param name="cacheOption"> /// [overrides all default values] custom api caching options (default: ApiCaching is NOT /// USED ) /// </param> /// <param name="rateLimitOption2"> /// [overrides all default values] custom rate limit handling options (default: rate-limiting /// is USED) default X-App-Rate-Limit: 100:120,20:1, default X-Method-Rate-Limit: /// 20000:10,1200000:600, default Mathlists X-Method-Rate-Limit: 500:10 /// </param> /// <exception cref="Exception"> /// A delegate callback throws an exception. /// </exception> public static void AddLeagueOfLegendsApi(this IServiceCollection services, string riotApiKey, Func <CacheOption, CacheOption> cacheOption, Func <RateLimitBuilder, RateLimitBuilder> rateLimitOption2) { //can convertable to json var riotGamesApiBuilder = RiotGamesApiBuilder(riotApiKey); var riotGamesApiOption = riotGamesApiBuilder.Build(); var cOptions = new CacheOption(); riotGamesApiOption.CacheOptions = cacheOption != null?cacheOption(cOptions) : cOptions; //RateLimitData limits = RateLimitData();//default settings RateLimitBuilder rlb = null; if (rateLimitOption2 != null) { //limits = rateLimitOption2(limits); //user settings rlb = rateLimitOption2(new RateLimitBuilder()); //user settings } else { rlb = RateLimitBuilder(); //default settings } riotGamesApiOption.RateLimitOptions.All = rlb.Build(); riotGamesApiOption.RateLimitOptions.SetLeagueApiLimit(rlb.Special_Leagues_Limits); riotGamesApiOption.RateLimitOptions.SetSummonerIdAndByNameApiLimit(rlb.SummonerIdAndByName_Limits); riotGamesApiOption.RateLimitOptions.SetSummonerAccountNameApiLimit(rlb.SummonerAccountName_Limits); riotGamesApiOption.RateLimitOptions.DisableLimiting = false; //force rate-limiting to use services.AddSingleton <IApiOption>(riotGamesApiOption); services.AddMemoryCache(); services.AddSingleton <IApiCache>(new ApiCache()); services.AddSingleton <LolApi>(new LolApi()); services.AddSingleton <LolApiRateLimit>(new LolApiRateLimit()); }
public Result Login([FromQuery] string username, [FromQuery] string password) { Result Result = new Result(); try { User user = UserService.GetUser(username); if (!UserService.CheckPassword(username, MD5Comm.Get32MD5One(password))) { return(Result.Fail("账号或密码错误!")); } //计算cookie的值 string cookieValue = MD5Comm.Get32MD5One(DateTime.Now.ToString()); Console.WriteLine("用户 : " + user.Name + ", token : " + cookieValue); //存入缓存 CacheOption.SetValue(cookieValue, user, DateTime.Now + TimeSpan.FromDays(100)); //默认10天有效 TokenInfo token = new TokenInfo(user.Name, DateTime.Now + TimeSpan.FromDays(10)); this.SetUserToken(token, user); Result.Data = new { IsSpecial = user.IsHasSpecialPower() || ishaveroot(user), Time = user.IsHasSpecialPower() ? ( DateTime.Now + TimeSpan.FromDays(30)).ToString() : (user.EndDate == null || user.EndDate < DateTime.Now ? "未开通会员" : user.EndDate.ToString()), IsShowMsg = (user.Email == null || user.Email.Equals("")).ToString(), Msg = "检测到您还没绑定邮箱,请有空尽快去绑定一下邮箱,群里有修改邮箱地址," + "绑定邮箱之后可以通过邮箱找回密码!", IsLogin = true, UserName = user.Name, EndTime = user.EndDate == null ? "" : user.EndDate.ToString() }; } catch (Exception ex) { Result.SetCode(ResultCode.Fail); Result.Msg = ex.Message; } return(Result); }
public static void AddNCache(this IServiceCollection services, Action <CacheOption> cacheAction) { CacheOption cacheOption = new CacheOption(); cacheAction.Invoke(cacheOption); switch (cacheOption.CacheType) { case CacheTypeEnum.Local: MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()); services.AddSingleton <IMemoryCache>(memoryCache); services.AddSingleton <ICacheRepository, MemoryCacheRepository>(); break; case CacheTypeEnum.Redis: if (cacheOption.RedisClient == null) { throw new ArgumentNullException(nameof(cacheOption.RedisClient)); } CSRedis.CSRedisClient cSRedis = cacheOption.RedisClient; RedisHelper.Initialization(cSRedis); services.AddSingleton <ICacheRepository, RedisCacheRepository>(); break; } }
/// <inheritdoc cref="IAsyncCachedQuery{TContext,TCacheEntryOptions,TResult}.Execute"/> public virtual async Task <TTransformedResult> Execute(TContext context, IAsyncCacheStore <TCacheEntryOptions> cacheStore, CacheOption cacheOption, CancellationToken cancellationToken) { var cachedResult = await GetCachedResult(context, cacheStore, cacheOption, cancellationToken).ConfigureAwait(false); return(await TransformCachedResult(cachedResult, cancellationToken).ConfigureAwait(false)); }
/// <inheritdoc cref="IAsyncCachedQuery{TContext,TCacheEntryOptions,TResult}.Execute"/> public virtual Task <TResult> Execute(TContext context, IAsyncCacheStore <TCacheEntryOptions> cacheStore, CacheOption cacheOption, CancellationToken cancellationToken) => GetCachedResult(context, cacheStore, cacheOption, cancellationToken);
/// <inheritdoc cref="ISyncCachedQuery{TContext,TCacheEntryOptions,TResult}.Execute"/> public virtual TTransformedResult Execute(TContext context, ISyncCacheStore <TCacheEntryOptions> cacheStore, CacheOption cacheOption) { var cachedResult = GetCachedResult(context, cacheStore, cacheOption); return(TransformCachedResult(cachedResult)); }
/// <inheritdoc cref="ISyncCachedQuery{TContext,TCacheEntryOptions,TResult}.Execute"/> public virtual TResult Execute(TContext context, ISyncCacheStore <TCacheEntryOptions> cacheStore, CacheOption cacheOption) => GetCachedResult(context, cacheStore, cacheOption);
/// <summary> /// 获取文件夹下文件列表自定义对象 /// </summary> /// <param name="directory">文件夹名称</param> /// <param name="searchPattern">文件搜索通配符</param> /// <param name="searchOption">文件搜索选项</param> /// <param name="regexPattern">文件搜索正值表达式</param> /// <param name="funcKey">委托参数KEY</param> /// <param name="searchFunc">委托函数</param> /// <param name="cacheType">缓存方式</param> /// <param name="cacheOption">缓存选项</param> /// <returns>返回文件列表缓存</returns> public static T GetFileInfos <T>(string directory, string searchPattern, SearchOption searchOption, string regexPattern, string funcKey, Func <DirectoryCacheResult, T> searchFunc, CacheType cacheType = CacheType.Hashtable, CacheOption cacheOption = CacheOption.All) { /*创建日志目录*/ if (!Directory.Exists(Path.GetDirectoryName(logfilename))) { Directory.CreateDirectory(Path.GetDirectoryName(logfilename)); } // 只有缓存选项是所有都缓存或一级缓存,才会缓存文件夹通配符搜索的文件列表结果 DirectoryCacheResult all = GetFileInfos(directory, searchPattern, searchOption, regexPattern, (cacheOption == CacheOption.All || cacheOption == CacheOption.SearchFiles) ? cacheType : CacheType.None); // 原始缓存结果,为NULL,或者状态失败,返回T默认值 if (all == null || !all.Success) { return(default(T)); } // 根据参数计算缓存KEY string key = string.Format("{0}|{1}", all.CacheKey, funcKey); SearchCacheResult searchCacheResult = null; // 根据传入缓存方式获取缓存存储对象 IStorageBase Storage = null; if (cacheType == CacheType.Redis) { Storage = StorageRedis.Instance; } else { Storage = StorageHashtable.Instance; } // 防止查询耗时长,此处读取用锁控制只缓存一次 lock (Storage.GetLock(key)) { bool UseCache = (cacheType != CacheType.None) && (cacheOption == CacheOption.All || cacheOption == CacheOption.DelegateResult); // 缓存方式不等于不缓存,缓存选项 if (UseCache) { searchCacheResult = Storage.GetCache <SearchCacheResult>(key); } // 当前目录没有缓存,或者缓存已经过期 if (searchCacheResult == null || searchCacheResult.LastWriteTime != all.LastWriteTime) { // 查询结果缓存,并返回 searchCacheResult = new SearchCacheResult() { CacheKey = key, LastWriteTime = all.LastWriteTime, // 调用外部委托方法 result = searchFunc(all) }; if (UseCache) { Storage.SetCache(key, searchCacheResult); } //#if DEBUG // DEBUG模式记录日志 File.AppendAllText(logfilename, string.Format("CacheKey={0}, IsCacheReturn={1}, LastWriteTime={2:yyyy-MM-dd HH:mm:ss}\r\n\r\n", key, false, searchCacheResult.LastWriteTime)); //#endif } else { //#if DEBUG // DEBUG模式记录日志 File.AppendAllText(logfilename, string.Format("CacheKey={0}, IsCacheReturn={1}, LastWriteTime={2:yyyy-MM-dd HH:mm:ss}\r\n\r\n", key, true, searchCacheResult.LastWriteTime)); //#endif } } return((T)searchCacheResult.result); }
public virtual Task <TResult> QueryAsync <TContext, TResult, TCacheEntryOptions>(IAsyncCachedQuery <TContext, TCacheEntryOptions, TResult> query, CacheOption cacheOption = CacheOption.Default) { return(Invoker.QueryAsync(query, GetContext <TContext>(), cacheOption)); }
private async Task BatchCache(object arg) { if (BatchCahceList.Count <= 0) { return; } try { int db = (int)(Identity % CacheUtils.EntityDBs); IRedisDatabase redis = _CacheClient.GetDb(db); ITransaction trans = redis.Database.CreateTransaction(); foreach (NList batch in BatchCahceList) { CacheOption option = (CacheOption)batch.Get <int>(0); Nuid entity_id = batch.Get <Nuid>(1); switch (option) { case CacheOption.SetEntity: { string entity_type = batch.Get <string>(2); string key = CacheUtils.BuildEntities(entity_id); Task task = trans.HashSetAsync(key, entity_id.Unique.ToString(), entity_type); } break; case CacheOption.DelEntity: { string entity_type = batch.Get <string>(2); EntityPrefab entity_prefab = Prefabs.GetEntity(entity_type); if (entity_prefab == null) { continue; } foreach (TablePrefab table_prefab in entity_prefab.tables.Values) { string table_key = CacheUtils.BuildTable(entity_id, table_prefab.name); Task table_task = trans.KeyDeleteAsync(table_key); } string field_key = CacheUtils.BuildFields(entity_id); Task field_task = trans.KeyDeleteAsync(field_key); string entity_key = CacheUtils.BuildEntities(entity_id); Task entity_task = trans.HashDeleteAsync(entity_key, entity_id.Unique.ToString()); } break; case CacheOption.SetField: { string field_name = batch.Get <string>(2); byte[] field_value = batch.Get <byte[]>(3); string key = CacheUtils.BuildFields(entity_id); Task task = trans.HashSetAsync(key, field_name, field_value); } break; case CacheOption.SetRow: { string table_name = batch.Get <string>(2); long row = batch.Get <long>(3); NList row_value = batch.Get <NList>(4); string key = CacheUtils.BuildTable(entity_id, table_name); Task task = trans.HashSetAsync(key, row, ProtoUtils.Serialize(row_value)); } break; case CacheOption.DelRow: { string table_name = batch.Get <string>(2); long row = batch.Get <long>(3); string key = CacheUtils.BuildTable(entity_id, table_name); Task task = trans.HashDeleteAsync(key, row); } break; case CacheOption.ClearTable: { string table_name = batch.Get <string>(2); string key = CacheUtils.BuildTable(entity_id, table_name); Task task = trans.KeyDeleteAsync(key); } break; default: break; } } bool result = await trans.ExecuteAsync(); if (result) { BatchCahceList.Clear(); } else { throw new Exception(); } } catch (Exception ex) { _Logger.LogError(ex, string.Format("{0} BatchCache ExecuteAsync Failed", Identity)); } }
/// <inheritdoc cref="ISyncQueryMediary.Query{TContext,TCacheEntryOptions,TResult}"/> public virtual TResult Query <TContext, TCacheEntryOptions, TResult>(ISyncCachedQuery <TContext, TCacheEntryOptions, TResult> query, TContext context, CacheOption cacheOption) { if (query == null) { throw new ArgumentNullException(nameof(query)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } return(Decorator.Decorate(GetOperationName(query, nameof(query.Execute)), () => query.Execute(context, GetSyncCacheStore <TCacheEntryOptions>(), cacheOption))); }
/// <inheritdoc cref="IAsyncQueryMediary.QueryAsync{TContext,TCacheEntryOptions,TResult}"/> public virtual Task <TResult> QueryAsync <TContext, TCacheEntryOptions, TResult>(IAsyncCachedQuery <TContext, TCacheEntryOptions, TResult> query, TContext context, CacheOption cacheOption, CancellationToken cancellationToken = default) { if (query == null) { throw new ArgumentNullException(nameof(query)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } return(Decorator.Decorate(GetOperationName(query, nameof(query.Execute)), () => query.Execute(context, GetAsyncCacheStore <TCacheEntryOptions>(), cacheOption, cancellationToken))); }