public ResponseModel Logout() { ResponseModel resp = new ResponseModel(); string token = Convert.ToString(Request.Headers["X-Authorized-Token"]); token = SecurityService.DecryptStringAES(token); RedisCacheService radisCacheService = new RedisCacheService(_radisCacheServerAddress); if (!radisCacheService.Exists(token)) { radisCacheService.Remove(token); } securityCaller newSecurityCaller = new securityCaller(); newSecurityCaller.Logout(new SecurityService(_connectioSting), token); resp.Status = true; resp.StatusCode = (int)EnumMaster.StatusCode.Success; resp.ResponseData = null; resp.Message = "Logout Successfully!"; return(resp); }
public CacheTests() { var configuration = new ConfigurationBuilder() //.AddInMemoryCollection() .Build(); //initiate ServiceCollection w/logging var services = new ServiceCollection() //.AddSingleton<IConfiguration>(configuration) .AddLogging(logging => { // logging.AddDebug(); // ApplicationLogging.LoggerFactory = logging.Services.BuildServiceProvider().GetRequiredService<ILoggerFactory>(); }) ; //todo: replace the below with IOptions? //_appConfig = configuration.GetSection(nameof(AppConfig)).Get<AppConfig>(); //add services //services.AddSingleton(p => _appConfig); //IHostEnvironment env = new HostingEnvironment { EnvironmentName = Environments.Development }; services.AddSingleton <RedisCacheService>(); //assign services to be tested var _serviceProvider = services.BuildServiceProvider(); _redisCacheSvc = _serviceProvider.GetRequiredService <RedisCacheService>(); }
public bool HadReceivedDailyMaterialCoupon(int accId, int groupId, int totalSeconds) { string key = RedisConsts.DailyMaterialCoupon + groupId.ToString() + accId.ToString(); var redisCacheService = new RedisCacheService(); return(redisCacheService.Set(key, true.ToString(), totalSeconds)); }
public CaptchaHelperModel SendAuthCode(CaptchaEnum captchaEnum, int accId, CaptchaPhoneEmailEnum typeEnum, string phoneOrEmail) { var redisCacheService = new RedisCacheService(); if (string.IsNullOrWhiteSpace(phoneOrEmail)) { throw new ArgumentNullException("phoneOrEmail", "手机号码邮箱地址为空"); } //获取失败次数 var strWrongTimesKey = GetWrongTimesKey(captchaEnum, accId); int iWrongTimes = redisCacheService.Get <int>(strWrongTimesKey); //判断验证码错误次数 if (iWrongTimes > _checkWrongTimes) { return(new CaptchaHelperModel(false, "验证码错误次数过多,请1小时后重试或联系客服", typeEnum)); } //获取验证码key var strCaptchaKey = GetCaptchaKey(captchaEnum, accId, phoneOrEmail); if (string.IsNullOrEmpty(strCaptchaKey)) { return(new CaptchaHelperModel(false, "错误的手机号或邮箱", typeEnum)); } //判断是否之前发过验证码 int iCaptcha = redisCacheService.Get <int>(strCaptchaKey); if (iCaptcha == 0) { iCaptcha = Helper.GetInt32(Helper.GetRandomNum(), 111111); } var smsStr = string.Format("【生意专家】您本次获取的验证码为:{0},此验证码{1}分钟内有效。维护您的数据安全是生意专家义不容辞的责任。", iCaptcha, _outTimeMinutes); var mailSend = new EmailSend(); var smsSend = new SmsSend(); var result = typeEnum == CaptchaPhoneEmailEnum.Phone ? smsSend.SendSys(phoneOrEmail, smsStr, 13) : mailSend.SendVerifiEmail(accId, "", phoneOrEmail, iCaptcha.ToString()); if (result) { _logger.Debug("发送验证码成功:" + iCaptcha); redisCacheService.Set(strCaptchaKey, iCaptcha, _outTimeMinutes * 60); return(new CaptchaHelperModel(true, "发送验证码成功", CaptchaPhoneEmailEnum.Email)); } else { return(new CaptchaHelperModel(false, "发送失败", CaptchaPhoneEmailEnum.Email)); } }
private static void ConfigureCacheTecnique(this IServiceCollection services, IConfiguration configuration) { var settings = configuration.GetSection(nameof(CacheSettings)).Get <CacheSettings>(); var serviceName = settings.Technique + "Service"; switch (serviceName) { case nameof(MemoryCacheService): services.AddMemoryCache(); services.AddScoped(typeof(ICache), typeof(MemoryCacheService)); break; case nameof(RedisCacheService): RedisCacheService.Configure(settings); services.AddScoped(typeof(ICache), typeof(RedisCacheService)); break; default: if (settings.Enabled) { var errorMessage = string.IsNullOrWhiteSpace(settings.Technique) ? "is null" : $"'{settings.Technique}' is unknown"; throw new System.Exception($"CacheSettings is Enabled, but the Technique {errorMessage}"); } // Avoid error ICache injection services.AddSingleton(typeof(ICache), typeof(NotImplementedCacheService)); break; } }
/// <summary> /// 去除couponCode /// </summary> /// <param name="couponCode"></param> private void RemoveCouponCode(string couponCode) { Task.Run(() => { var redis = new RedisCacheService(); redis.SetRemove(RedisConsts.OrderCouponIdSet, couponCode); }); }
public bool IsHasDailyMaterialCoupon(int accId, int groupId) { string key = RedisConsts.DailyMaterialCoupon + groupId.ToString() + accId.ToString(); var redisCacheService = new RedisCacheService(); var redisvalue = redisCacheService.Get(key); return(redisvalue != "True"); }
/// <summary> /// 更新支出分类Redis缓存数据 /// </summary> /// <param name="userContext"></param> private void UpdateRedisPayClassCatch(UserContext userContext) { var redisCacheService = new RedisCacheService(); var currentNeedCatchData = GetExpensesCategoryFromDb(userContext); var setCatchKey = string.Format("I200:{0}:{1}", RedisConsts.PayClassList, userContext.AccId); redisCacheService.Set(setCatchKey, currentNeedCatchData, catchTime * 60); }
/// <summary> /// 添加优惠券数组到redis中 /// </summary> /// <returns></returns> private void AddCouponArrayToRedis() { lock (LockOrderCouonObject) { string[] couponArray = GetAllCouponArray(); var redis = new RedisCacheService(); redis.SetAdd(RedisConsts.OrderCouponIdSet, couponArray); } }
private RedisCacheService RegisterCacheService(IComponentContext context) { var configuration = context.Resolve <RedisConfiguration>(); var db = context.Resolve <IDatabase>(); var service = new RedisCacheService(db, configuration.KeyPrefix); return(service); }
public void InitTest() { _mockRepository = new MockRepository(MockBehavior.Strict); _dataBase = _mockRepository.Create <IDatabase>(); _target = new RedisCacheService(_dataBase.Object, null, _serializerSettings); _fixture = new Fixture(); }
/// <summary> /// 获取支出分类 /// </summary> /// <returns></returns> public ResponseModel GetExpensesCategory(UserContext userContext) { var setCatchKey = string.Format("I200:{0}:{1}", RedisConsts.PayClassList, userContext.AccId); var redisCacheService = new RedisCacheService(); var data = redisCacheService.Get <PayClassResult>(setCatchKey); return(new ResponseModel { Code = (int)ErrorCodeEnum.Success, Data = data ?? GetExpensesCategoryFromDb(userContext) }); }
/// <summary> /// 生成优惠券到redis集合set,成功返回true,失败返回false /// </summary> /// <param name="couponCode"></param> /// <param name="isFirst"></param> /// <returns></returns> private bool CreateCouponToRedisSet(string couponCode, bool isFirst) { //首次添加查询是否存在key if (isFirst) { var redisCacheService = new RedisCacheService(); if (!redisCacheService.HasKey(RedisConsts.OrderCouponIdSet)) { AddCouponArrayToRedis(); } } return(AddCouponToRedis(couponCode)); }
/// <summary> /// 更新远程redis缓存到本地 /// </summary> /// <param name="key"></param> public void UpdateLocalConfig(string key) { var redisCacheService = new RedisCacheService(); if (!redisCacheService.HasKey(key)) { throw new YuanbeiException("config key {0} not existed in redis", key); } string val = redisCacheService.Get <string>(key); _localCache.Set(key, val, _configLastMinutes); }
public void TestRedisCache() { IConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(configuration: "localhost:6379"); ICacheService cacheService = new RedisCacheService(connectionMultiplexer); string keyItemCache = "UnitTest"; var result = cacheService.GetCacheValueAsync(keyItemCache).GetAwaiter().GetResult(); Assert.IsNull(result); cacheService.SetCacheValueAsync(keyItemCache, "Some text here.").GetAwaiter(); result = cacheService.GetCacheValueAsync(keyItemCache).GetAwaiter().GetResult(); Assert.IsNotNull(result); }
public async Task <ResponseMessage> ExecuteRedisCommand(Command command) { if (command.DatabaseId == null) { return(new ResponseMessage { Status = Status.fail, Error = "No Database Id provided." }); } var data = string.Empty; RedisCacheService redisCacheService = new RedisCacheService(command); try { switch (command.CommandType) { case CommandType.ClearAll: await redisCacheService.Clear(); break; case CommandType.GetValue: data = await redisCacheService.Get(); break; case CommandType.Remove: await redisCacheService.Remove(); break; } } catch (Exception ex) { return(new ResponseMessage { Status = Status.fail, Error = ex.Message }); } return(new ResponseMessage { Status = Status.success, Data = !string.IsNullOrEmpty(data) ? data : null }); }
private static void InitPropertyCacheConnection() { try { if (isExpressionCacheEnabled && (ExpressionCacheService == null || !ExpressionCacheService.IsConnectionActive())) { ExpressionCacheService = new RedisCacheService(KLMExpressionCacheUrl, 6379); } } catch (Exception ex) { ConsoleLogger.Write($"ERROR: CACHE InitPropertyCacheConnection - {ex.ToString()}"); } }
public void BuildCacheKeyFromUrl_AppendsForwardSlash() { var testOid = Guid.NewGuid(); var testUrl = "https://localhost/api/Sites"; // Arrange var expectedCacheKey = $"{testOid}|/api/sites/"; // Act var cacheService = new RedisCacheService(null, new Data.Constants.RedisSettings { IsEnabled = true, TimeToLiveSeconds = 0 }); var actualCacheKey = cacheService.BuildCacheKeyFromUrl(testUrl, testOid); // Assert Assert.Equal(expectedCacheKey, actualCacheKey); }
public CaptchaHelperModel CheckCaptchaCode(CaptchaEnum captchaEnum, int accId, CaptchaPhoneEmailEnum typeEnum, int captchaCode, string phoneOrEmail) { var redisCacheService = new RedisCacheService(); CaptchaHelperModel model; //获取失败次数 var strWrongTimesKey = GetWrongTimesKey(captchaEnum, accId); int iWrongTimes = redisCacheService.Get <int>(strWrongTimesKey); //判断验证码错误次数 if (iWrongTimes > 10) { return(new CaptchaHelperModel(false, "验证码错误次数过多,请1小时后重试或联系客服", typeEnum)); } //获取验证码key string strCaptchaKey = GetCaptchaKey(captchaEnum, accId, phoneOrEmail); if (string.IsNullOrWhiteSpace(strCaptchaKey)) { return(new CaptchaHelperModel(false, "验证码校验失败", typeEnum)); } //获取发过的验证码 int iCaptcha = redisCacheService.Get <int>(strCaptchaKey); if (iCaptcha == captchaCode) { _logger.Debug("验证验证码成功:" + iCaptcha); redisCacheService.RemoveKey(strWrongTimesKey); redisCacheService.RemoveKey(strCaptchaKey); return(new CaptchaHelperModel(true, "验证码校验成功", typeEnum)); } else if (iCaptcha == 0) { _logger.Debug("验证验证码失败:" + captchaCode); return(new CaptchaHelperModel(false, "验证码过期,请重新申请发送验证码", typeEnum)); } else { //失败添加失败次数 redisCacheService.Set(strWrongTimesKey, iWrongTimes + 1, 60 * 60); return(new CaptchaHelperModel(false, "验证码校验失败", typeEnum)); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RedisCacheService redisCacheService) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); redisCacheService.Connect(); }
/// <summary> /// 获取城市列表(包括省列表、城市列表) /// </summary> /// <returns></returns> public ResponseModel GetProvinceCityList() { var catchTime = 1440 * 60; var redisCacheService = new RedisCacheService(); return(new ResponseModel { Code = (int)ErrorCodeEnum.Success, Data = redisCacheService.Get(RedisConsts.ConstructedProvinceCityList, () => { { { // ReSharper disable once AccessToDisposedClosure var basedata = redisCacheService.Get(RedisConsts.AddressBaseData, catchTime, GetAllProvinceFromDb); // 获取省列表 var provinceList = basedata.Where(a => a.Level == 1); var result = new Address.RetAddressData(); // 遍历省列表追加市列表 foreach (var province in provinceList) { var provinceSelfId = province.SelfId; var provinceModel = new Address.Province { Id = province.Id, Name = province.Name }; result.ProvinceList.Add(provinceModel); var cities = basedata.Where(a => a.Level == 2 && a.ParentId == provinceSelfId); result.CityList.Add(new Address.City { ProvinceId = province.Id, CityValues = cities.Select(c => new Address.CityValues { CityId = c.Id, CityName = c.Name }) .ToList() }); } return result; } } }) }); }
public ResponseModel UpdatePassword(string cipherEmailId, string Password) { ResponseModel objResponseModel = new ResponseModel(); try { StoreSecurityCaller newSecurityCaller = new StoreSecurityCaller(); CommonService commonService = new CommonService(); EmailProgramCode bsObj = new EmailProgramCode(); string encryptedEmailId = commonService.Decrypt(cipherEmailId); if (encryptedEmailId != null) { bsObj = JsonConvert.DeserializeObject <EmailProgramCode>(encryptedEmailId); } string _data = ""; if (bsObj.ProgramCode != null) { // bsObj.ProgramCode = SecurityService.DecryptStringAES(bsObj.ProgramCode); RedisCacheService cacheService = new RedisCacheService(_radisCacheServerAddress); if (cacheService.Exists("Con" + bsObj.ProgramCode)) { _data = cacheService.Get("Con" + bsObj.ProgramCode); _data = JsonConvert.DeserializeObject <string>(_data); } } bool isUpdate = newSecurityCaller.UpdatePassword(new StoreSecurityService(_data), bsObj.EmailID, Password); if (isUpdate) { objResponseModel.Status = true; objResponseModel.StatusCode = (int)EnumMaster.StatusCode.Success; objResponseModel.Message = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)(int) EnumMaster.StatusCode.Success); objResponseModel.ResponseData = "Update password successfully"; } } catch (Exception) { throw; } return(objResponseModel); }
public string GetConfig(string key) { if (_localCache.IsSet(key)) { return(_localCache.Get <string>(key)); } var redisCacheService = new RedisCacheService(); if (!redisCacheService.HasKey(key)) { throw new YuanbeiException("config key {0} not existed in redis", key); } string val = redisCacheService.Get <string>(key); _localCache.Set(key, val, _configLastMinutes); return(val); }
private static void InitCacheConnection() { try { if (isApiCacheEnabled && (ApiCacheService == null || !ApiCacheService.IsConnectionActive())) { ApiCacheService = new RedisCacheService(KLMApiCacheUrl, 6379); } if (isWebCacheEnabled && (WebCacheService == null || !WebCacheService.IsConnectionActive())) { WebCacheService = new RedisCacheService(KLMWebCacheUrl, 6379); } } catch (Exception ex) { ConsoleLogger.Write($"ERROR: CACHE InitCacheConnection - {ex.ToString()}"); } }
/// <summary> /// 定义通用访问入口,默认使用运行时缓存 /// </summary> /// <returns></returns> public static ICacheService GetCache() { switch (CacheType) { case CacheType.Runtime: return(RuntimeCacheService.GetCacheInstance()); case CacheType.Redis: return(RedisCacheService.GetCacheInstance()); case CacheType.Memcached: return(MemcachedCacheService.GetCacheInstance()); case CacheType.MemoryCache: return(MemoryCacheService.GetCacheInstance()); default: return(RuntimeCacheService.GetCacheInstance()); } }
public BaseUnitTest(ITestOutputHelper output) { _redisCacheService = new RedisCacheService(new RedisConfig() { Ip = "122.114.19.229", Port = 6379, DataBase = 3, Name = "einfrastructure_", Password = "******", PoolSize = 1, OverTimeCacheKeyPre = "OverTime_HashSet", }, new List <IJsonProvider>() { new NewtonsoftJsonProvider() }); // var connectionString = ""; // var services = new ServiceCollection(); // this.output = output; // services.AddSingleton<IRandomBuilder, RandomCommon>(); // provider = services.BuildServiceProvider(); }
/// <summary> /// redis获取商品详情 /// </summary> /// <param name="goodsId"></param> /// <returns></returns> private MaterialGoodsInfo GetMaterialGoodsDetails(int goodsId) { MaterialGoodsInfo entity; string key = RedisConsts.MaterialGoodsInfo + goodsId; var redisCacheService = new RedisCacheService(); if (redisCacheService.HasKey(key)) { entity = redisCacheService.Get <MaterialGoodsInfo>(key); } else { entity = GetMaterialGoodsDb(goodsId); //Insert Cache 7days Task.Factory.StartNew(() => { redisCacheService.Set(key, entity, 60 * 60 * 24 * 7); }); } return(entity); }
/// <summary> /// 根据ID获取硬件商品相应数据 /// 新方法更快 /// </summary> /// <param name="gidInts"></param> /// <returns></returns> private List <IndexMaterialGoods> GetIndexMaterialGoodses2(IEnumerable <int> gidInts) { var rList = new List <IndexMaterialGoods>(); var mList = new List <MaterialGoodsInfo>(); var goodsList = GetMaterialGoodsIdList(); if (goodsList.Any() && gidInts.Any()) { var redisCacheService = new RedisCacheService(); mList = redisCacheService .Get <MaterialGoodsInfo>( gidInts.Select(x => RedisConsts.MaterialGoodsInfo + x.ToString()).ToArray()) .ToList(); if (gidInts.Count() != mList.Count) { mList.AddRange( gidInts .Except(mList.Select(x => x.GoodsId)) .Select(GetMaterialGoodsDetails) ); } } if (mList.Any()) { rList.AddRange(mList.Select(goods => new IndexMaterialGoods { Id = goods.Id, GoodsId = goods.GoodsId, AliasName = goods.AliasName, Price = goods.Price, Status = goods.Status, RankNo = goods.RankNo, ClassId = goods.ClassId, CoverImage = goods.CoverImage })); return(rList.OrderBy(x => x.RankNo).ToList()); } return(null); }
/// <summary> /// 根据省Id和城市id获取对应的名称 /// </summary> /// <returns></returns> public Tuple <string, string> GetProvinceAndCityNameById(int provinceId, int cityId) { var catchTime = 1440 * 60; if (provinceId == 1) { return(new Tuple <string, string>("北京", "北京")); } if (provinceId == 153) { return(new Tuple <string, string>("上海", "上海")); } if (provinceId == 342) { return(new Tuple <string, string>("重庆", "重庆")); } if (provinceId == 294) { return(new Tuple <string, string>("天津", "天津")); } var redisCacheService = new RedisCacheService(); var allProvince = redisCacheService.Get(RedisConsts.AddressBaseData, catchTime, GetAllProvinceFromDb); var province = allProvince.SingleOrDefault(a => a.Id == provinceId && a.Level == 1); if (province == null) { throw new YuanbeiException("未找到对应的省:" + provinceId); } var city = allProvince.SingleOrDefault(a => a.Id == cityId && a.Level == 2); if (city == null) { throw new YuanbeiException("未找到对应的市:" + cityId); } return(new Tuple <string, string>(province.Name, city.Name)); }
/// <summary> /// redis获取商品列表 /// </summary> /// <returns></returns> private IEnumerable <MaterialGoodsListRedisItem> GetMaterialGoodsIdList() { IEnumerable <MaterialGoodsListRedisItem> rModel; string key = RedisConsts.MaterialGoodsList; var redisCacheService = new RedisCacheService(); if (redisCacheService.HasKey(key)) { rModel = redisCacheService.Get <List <MaterialGoodsListRedisItem> >(key); } else { rModel = Mapper.Map <IEnumerable <T_MaterialGoods2>, IEnumerable <MaterialGoodsListRedisItem> >(_materialGoods.FindAll()); //Insert Cache 7days Task.Factory.StartNew(() => { redisCacheService.Set(key, rModel, 60 * 60 * 24 * 7); }); } return(rModel); }