public string HH() { string returnStr = "HAHA"; if (_cach.Get("1") != null) { returnStr = _cach.Get("1").ToString(); } else { _cach.Set("1", "Set 1!!!!"); } return(returnStr); }
public List <PetOwnerPerson> GetAllPetOwnerDetails() { try { string petOwnerResultStream; bool isProxyEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings[Constants.UseProxy]); ProxyDetail proxyDetail = null; if (isProxyEnabled) { proxyDetail = new ProxyDetail { Url = ConfigurationManager.AppSettings[Constants.ProxyUrl], Port = ConfigurationManager.AppSettings[Constants.ProxyPort] }; } var headerDetails = new Dictionary <string, string> { { "User-Agent", ConfigurationManager.AppSettings[Constants.ExtApiUserAgent] } }; bool isMemoryCacheEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings[Constants.MemCacheAppSettings]); if (isMemoryCacheEnabled) { if (_cache.Get(Constants.PetOwnerCache, false) == null) { petOwnerResultStream = ApiHandler.GetApiResult(ConfigurationManager.AppSettings[Constants.ApiUrl], headerDetails, isProxyEnabled, proxyDetail); _cache.Set(Constants.PetOwnerCache, petOwnerResultStream, false, null); } else { petOwnerResultStream = Convert.ToString(_cache.Get(Constants.PetOwnerCache, false)); } } else { petOwnerResultStream = ApiHandler.GetApiResult(ConfigurationManager.AppSettings[Constants.ApiUrl], headerDetails, isProxyEnabled, proxyDetail); } return(JsonConvert.DeserializeObject <List <PetOwnerPerson> >(petOwnerResultStream)); } catch (Exception ex) { Logging.HandleException(ex); throw; } }
/// <summary> /// 拦截方法 /// </summary> /// <param name="invocation"></param> public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; // 对当前方法的特性验证 if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) is CachingAttribute qCachingAttribute) { // 获取自定缓存键 var cacheKey = CustomCacheKey(invocation); var cacheValue = _cache.Get(cacheKey); if (cacheValue != null) { // 获取当前的缓存值,并作为返回值返回 invocation.ReturnValue = cacheValue; return; } // 继续执行当前请求 invocation.Proceed(); // 存入缓存 if (string.IsNullOrWhiteSpace(cacheKey)) { _cache.Set(cacheKey, invocation.ReturnValue); } } else { invocation.Proceed(); } }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 //如果需要验证 if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) is CachingAttribute qCachingAttribute) { //获取自定义缓存键 var cacheKey = CustomCacheKey(invocation); //根据key获取相应的缓存值 var cacheValue = _cache.Get(cacheKey); if (cacheValue != null) { //将当前获取到的缓存值,赋值给当前执行方法 invocation.ReturnValue = cacheValue; return; } //去执行当前的方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { _cache.Set(cacheKey, invocation.ReturnValue); } } else { invocation.Proceed();//直接执行被拦截方法 } }
public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) is CachingAttribute cachingAttribute) { //获取自定义缓存键 var cacheKey = CustomCacheKey(invocation); //根据key获取相应的缓存值 var cacheValue = _cache.Get(cacheKey); if (cacheValue != null) { invocation.ReturnValue = cacheValue; return; } //执行当前方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { _cache.Set(cacheKey, invocation.ReturnValue, TimeSpan.FromMinutes(cachingAttribute.AbsoluteExpiration)); } } else { invocation.Proceed();//直接执行被拦截方法 } }
//Intercept方法是攔截的關鍵所在,也是IInterceptor接口中的唯一定義 public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //對當前方法的特性驗證 //如果需要驗證 if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) is CachingAttribute qCachingAttribute) { //獲取自定義緩存鍵 var cacheKey = CustomCacheKey(invocation); //根據key獲取相應的緩存值 var cacheValue = _cache.Get(cacheKey); if (cacheValue != null) { //將當前獲取到的緩存值,賦值給當前執行方法 invocation.ReturnValue = cacheValue; return; } //去執行當前的方法 invocation.Proceed(); //存入緩存 if (!string.IsNullOrWhiteSpace(cacheKey)) { _cache.Set(cacheKey, invocation.ReturnValue); } } else { invocation.Proceed();//直接執行被攔截方法 } }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCachingAttribute != null) { // 获取自定义缓存键 var cacheKey = CustomCacheKey(invocation); var cacheValue = _cache.Get(cacheKey); if (cacheValue != null) { // 将当前获取到的缓存值,赋值给当前执行方法 invocation.ReturnValue = cacheValue; return; } // 执行当前的方法 invocation.Proceed(); if (!string.IsNullOrWhiteSpace(cacheKey)) { _cache.Set(cacheKey, invocation.ReturnValue); } } else { invocation.Proceed(); } }
public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) is CachingAttribute qCachingAttribute) { var cachekey = CustomCacheKey(invocation); var cachevalue = _cache.Get(cachekey); if (cachevalue != null) { invocation.ReturnValue = cachevalue; return; } invocation.Proceed(); if (!string.IsNullOrWhiteSpace(cachekey)) { _cache.Set(cachekey, invocation.ReturnValue); } } else { invocation.Proceed(); } }
public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; var qCacheingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCacheingAttribute != null) { var expirationTime = qCacheingAttribute.AbsoluteExpiration; var cacheKey = CustomCacheKey(invocation); var cacheValue = _cache.Get(cacheKey); if (cacheValue != null) { invocation.ReturnValue = cacheValue; return; } invocation.Proceed(); if (!string.IsNullOrWhiteSpace(cacheKey)) { _cache.Set(cacheKey, invocation.ReturnValue); } } else { invocation.Proceed(); } }
public ActionResult <BaseResponse> Login(LoginRequest request) { //admin 123456 var user = _accountStoreService.QueryUserByName(request.Username); if (user == null) { return(BaseResponse.GetBaseResponse(ResponseStatusType.Failed, "用户名错误")); } if (user.Password != request.Password) { return(BaseResponse.GetBaseResponse(ResponseStatusType.Failed, "密码错误")); } var tokenCacheKey = CacheKey.Token(user.Id.ToString()); var token = _caching.Get <Token>(tokenCacheKey); if (token == null) { //新登录用户 创建新Token token = GenerateToken(user); _caching.Set(tokenCacheKey, token, TimeSpan.FromDays(_jwtConfig.RefreshTokenExpiresDays)); } else { //老用户 var expires = FormatHelper.ConvertToDateTime(token.AccessTokenExpires); if (expires <= DateTime.Now) { //AccessTokeng过期 重新生成 var newToken = GenerateToken(user); //只更新AccessToken,老的RefreshToken保持不变 token.AccessToken = newToken.AccessToken; token.AccessTokenExpires = newToken.AccessTokenExpires; var refreshTokenExpires = FormatHelper.ConvertToDateTime(token.RefreshTokenExpires); var expireTimeSpan = refreshTokenExpires - DateTime.Now; _caching.Set(tokenCacheKey, token, expireTimeSpan); } } UpdateLastLoginInfo(user); return(BaseResponse <Token> .GetBaseResponse(token)); }
/// <summary> /// 异步从缓存里取数据,如果不存在则执行查询方法 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="cache">ICaching </param> /// <param name="key">键值</param> /// <param name="GetFun">查询方法</param> /// <param name="timeSpanMin">有效期 单位分钟/param> /// <returns></returns> public static async Task <T> Cof_AsyncGetICaching <T>(this ICaching cache, string key, Func <Task <T> > GetFun, int timeSpanMin) where T : class { var obj = cache.Get(key); if (obj == null) { obj = await GetFun(); cache.Set(key, obj, timeSpanMin); } return(obj as T); }
public IEnumerable <PetOwnerPerson> GetAllPetOwner() { try { string _petOwnerResultStream; bool _isProxyEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings[Constants.UseProxy]); ProxyDetail _proxyDetail = null; if (_isProxyEnabled) { _proxyDetail = new ProxyDetail { Url = ConfigurationManager.AppSettings[Constants.ProxyUrl].ToString(), Port = ConfigurationManager.AppSettings[Constants.ProxyPort].ToString() }; } Dictionary <string, string> _headerDetails = new Dictionary <string, string>(); _headerDetails.Add("User-Agent", ConfigurationManager.AppSettings[Constants.ExtApiUserAgent].ToString()); bool _isMemoryCacheEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings[Constants.MemCacheAppSettings]); //Check in Cache if (_isMemoryCacheEnabled) { if (null == this.cache.Get(Constants.PetOwnerCache, false)) { _petOwnerResultStream = APIHandler.GetAPIResult(ConfigurationManager.AppSettings[Constants.ApiUrl], _headerDetails, _isProxyEnabled, _proxyDetail); //.Result; // httpClient.GetStringAsync(new Uri(ConfigurationManager.AppSettings[Constants.ApiUrl])).Result; cache.Set(Constants.PetOwnerCache, _petOwnerResultStream, false, null); } else { _petOwnerResultStream = Convert.ToString(cache.Get(Constants.PetOwnerCache, false)); } } else { _petOwnerResultStream = APIHandler.GetAPIResult(ConfigurationManager.AppSettings[Constants.ApiUrl], _headerDetails, _isProxyEnabled, _proxyDetail); } JsonSerializerSettings settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore }; return(JsonConvert.DeserializeObject <List <PetOwnerPerson> >(_petOwnerResultStream, settings)); } catch (Exception ex) { Logging.HandleException(ex); throw; } }
/// <summary> /// 从缓存里取数据,如果不存在则执行查询方法, /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="cache">ICaching </param> /// <param name="key">键值</param> /// <param name="GetFun">查询方法</param> /// <param name="timeSpanMin">有效期 单位分钟/param> /// <returns></returns> public static T Cof_GetICaching <T>(this ICaching cache, string key, Func <T> GetFun, int timeSpanMin) where T : class { var obj = cache.Get(key); obj = GetFun(); if (obj == null) { obj = GetFun(); cache.Set(key, obj, timeSpanMin); } return(obj as T); }
public async Task <GuidDataModel> Get(Guid guid) { var item = _cache.Get <GuidDataModel>(guid); if (item != null) { return(item); } else { item = await _context.GuidList.FindAsync(guid); _cache.Add <GuidDataModel>(guid, item); } if (item == null) { throw new RecordNotFound(Constants.GUID_NOT_FOUND); } return(item); }
public PasswdProvider( IUserDataAccess userDataAccess, IGroupDataAccess groupDataAccess, ICaching cache, ILogger log, IConfigValues config) { _cache = cache; _log = log; _config = config; CacheItem cachedUser = _cache.Get(USER_CACHE_KEY); CacheItem cachedGroup = _cache.Get(GROUP_CACHE_KEY); if (null == cachedUser || null == cachedUser.Obj || cachedUser.TimeAddedUTC < getUsersLastModified(userDataAccess, log, config)) { _users = loadUsers(userDataAccess, log, config, cache, cachedUser); } else { _users = (Users)cachedUser.Obj; } if (null == cachedGroup || null == cachedGroup.Obj || cachedGroup.TimeAddedUTC < getGroupLastModified(groupDataAccess, log, config)) { _groups = loadGroups(groupDataAccess, log, config, cache, cachedGroup); } else { _groups = (Groups)cachedGroup.Obj; } }
public override void Intercept(IInvocation invocation) { #region 加特性验证 ////获取自定义缓存键 //var cacheKey = CustomCacheKey(invocation); ////根据key获取相应的缓存值 //var cacheValue = _cache.Get(cacheKey); //if (cacheValue != null) //{ // //将当前获取到的缓存值,赋值给当前执行方法 // invocation.ReturnValue = cacheValue; // return; //} ////去执行当前的方法 //invocation.Proceed(); ////存入缓存 //if (!string.IsNullOrWhiteSpace(cacheKey)) //{ // _cache.Set(cacheKey, invocation.ReturnValue); //} #endregion var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法特性验证 var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCachingAttribute != null) { var cacheKey = CustomCacheKey(invocation); var cacheValue = _cache.Get(cacheKey); if (cacheValue != null) { invocation.ReturnValue = cacheValue; return; } invocation.Proceed(); if (!string.IsNullOrWhiteSpace(cacheKey)) { _cache.Set(cacheKey, invocation.ReturnValue); } } else { invocation.Proceed();//直接执行被拦截方法 } }
public string GetSetting(string settingKey) { string value = _caching.Get <string>(settingKey, Constants.CONFIGURATION_SECTION); if (value != null) { return(value); } Core.Common.Configurations.Configuration item = _configurationRepository.Get(settingKey); if (item == null) { throw new ConfigurationException(settingKey); } SetCache(settingKey, item.Value); return(item.Value); }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 public void Intercept(IInvocation invocation) { //获取自定义缓存键 var chacheKey = CustomCacheKey(invocation); var cacheValue = _caching.Get(chacheKey); if (cacheValue != null) { //将当前获取到的缓存值,赋值给当前执行的方法。 invocation.ReturnValue = cacheValue; return; } //执行当前的方法。 invocation.Proceed(); if (!string.IsNullOrEmpty(chacheKey)) { //存入缓存 _caching.Set(chacheKey, invocation.ReturnValue); } }
public void Intercept(IInvocation invocation) { string cacheKey = GetCustomKey(invocation); object data = _cache.Get(cacheKey); if (data != null) { invocation.ReturnValue = data; return; } else { invocation.Proceed(); object rValue = invocation.ReturnValue; if (rValue != null && !string.IsNullOrWhiteSpace(cacheKey)) { _cache.Set(cacheKey, rValue); } } }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 public override void Intercept(IInvocation invocation) { //获取自定义缓存键 var cacheKey = CustomCacheKey(invocation); //根据key获取相应的缓存值 var cacheValue = _cache.Get(cacheKey); if (cacheValue != null) { //将当前获取到的缓存值,赋值给当前执行方法 invocation.ReturnValue = cacheValue; return; } //去执行当前的方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { _cache.Set(cacheKey, invocation.ReturnValue); } }
public async Task <MessageEntity> FileMerge([FromBody] Dictionary <string, object> fileInfo) { MessageEntity message = new MessageEntity(); string fileName = string.Empty; if (fileInfo.ContainsKey("name")) { fileName = fileInfo["name"].ToString(); } if (string.IsNullOrEmpty(fileName)) { message.Code = -1; message.Msg = "文件名不能为空"; return(message); } //最终上传完成后,请求合并返回合并消息 try { RequestFileUploadEntity requestFile = _cache.Get(fileName) as RequestFileUploadEntity; if (requestFile == null) { message.Code = -1; message.Msg = "合并失败"; return(message); } string filePath = $".{Appsettings.app(new string[] { "TestFileHandle", "FilePath" })}{DateTime.Now.ToString("yyyy-MM-dd")}/{fileName}"; string fileExt = requestFile.fileext; string fileMd5 = requestFile.filedata; int fileCount = requestFile.count; long fileSize = requestFile.size; string fileTestname = requestFile.filename; //LogUtil.Debug($"获取文件路径:{filePath}"); //LogUtil.Debug($"获取文件类型:{fileExt}"); string savePath = filePath.Replace(fileName, ""); string saveFileName = $"{fileTestname}"; var files = Directory.GetFiles(filePath); string fileFinalName = Path.Combine(savePath, saveFileName); //LogUtil.Debug($"获取文件最终路径:{fileFinalName}"); FileStream fs = new FileStream(fileFinalName, FileMode.Create); //LogUtil.Debug($"目录文件下文件总数:{files.Length}"); //LogUtil.Debug($"目录文件排序前:{string.Join(",", files.ToArray())}"); //LogUtil.Debug($"目录文件排序后:{string.Join(",", files.OrderBy(x => x.Length).ThenBy(x => x))}"); byte[] finalBytes = new byte[fileSize]; foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x)) { var bytes = System.IO.File.ReadAllBytes(part); await fs.WriteAsync(bytes, 0, bytes.Length); bytes = null; System.IO.File.Delete(part);//删除分块 } fs.Close(); //这个地方会引发文件被占用异常 fs = new FileStream(fileFinalName, FileMode.Open); string strMd5 = GetCryptoString(fs); //LogUtil.Debug($"文件数据MD5:{strMd5}"); //LogUtil.Debug($"文件上传数据:{JsonConvert.SerializeObject(requestFile)}"); fs.Close(); Directory.Delete(filePath); //如果MD5与原MD5不匹配,提示重新上传 if (strMd5 != requestFile.filedata) { //LogUtil.Debug($"上传文件md5:{requestFile.filedata},服务器保存文件md5:{strMd5}"); message.Code = -1; message.Msg = "MD5值不匹配"; return(message); } _cache.Remove(fileInfo["name"].ToString()); message.Code = 0; message.Msg = ""; } catch (Exception ex) { //LogUtil.Error($"合并文件失败,文件名称:{fileName},错误信息:{ex.Message}"); message.Code = -1; message.Msg = "合并文件失败,请重新上传"; } return(message); }
public string policy() { string cacheString = cache_.Get("1")?.ToString(); return(tt.Name() + cacheString); }