public void Can_Replace_By_Pattern() { var model = ModelWithIdAndName.Create(1); string modelKey = "model:" + model.CreateUrn(); cacheClient.Add(modelKey, model); model = ModelWithIdAndName.Create(2); string modelKey2 = "xxmodelxx:" + model.CreateUrn(); cacheClient.Add(modelKey2, model); string s = "this is a string"; cacheClient.Add("string1", s); cacheClient.RemoveByPattern("*model*"); ModelWithIdAndName result = cacheClient.Get <ModelWithIdAndName>(modelKey); Assert.That(result, Is.Null); result = cacheClient.Get <ModelWithIdAndName>(modelKey2); Assert.That(result, Is.Null); string result2 = cacheClient.Get <string>("string1"); Assert.That(result2, Is.EqualTo(s)); cacheClient.RemoveByPattern("string*"); result2 = cacheClient.Get <string>("string1"); Assert.That(result2, Is.Null); }
public IDisposable AcquireLock(string name, TimeSpan?lockTimeout = null, TimeSpan?acquireTimeout = null) { Log.Trace().Message("AcquireLock: {0}", name).Write(); if (!acquireTimeout.HasValue) { acquireTimeout = TimeSpan.FromMinutes(1); } string cacheKey = GetCacheKey(name); Run.UntilTrue(() => { Log.Trace().Message("Checking to see if lock exists: {0}", name).Write(); var lockValue = _cacheClient.Get <object>(cacheKey); Log.Trace().Message("Lock: {0} Value: {1}", name, lockValue ?? "<null>").Write(); if (lockValue != null) { return(false); } Log.Trace().Message("Lock doesn't exist: {0}", name).Write(); if (lockTimeout.HasValue && lockTimeout.Value == TimeSpan.Zero) { return(_cacheClient.Add(cacheKey, DateTime.Now)); } return(_cacheClient.Add(cacheKey, DateTime.Now, lockTimeout ?? TimeSpan.FromMinutes(20))); }, acquireTimeout, TimeSpan.FromMilliseconds(50)); Log.Trace().Message("Returning lock: {0}", name).Write(); return(new DisposableLock(name, this)); }
public void CacheAllStocks(List <StockSymbol> allStocks) { //var serializer = new NewtonsoftSerializer(); //var cacheClient = new StackExchangeRedisCacheClient(serializer); string key = "StocksDecisionAllStocks"; stackCache.Remove(key); stackCache.Add(key, allStocks, DateTimeOffset.Now.AddHours(156)); }
public void Does_only_add_if_key_does_not_exist() { Assert.IsTrue(cache.Add("Car", "Audi")); Assert.That(cache.Get <string>("Car"), Is.EqualTo("Audi")); Assert.IsFalse(cache.Add("Car", "Ford")); Assert.That(cache.Get <string>("Car"), Is.EqualTo("Audi")); cache.Remove("Car"); }
public void AddCache <T>(string key, T value, DateTime expire) { if (value == null) { RemoveCache(key); } else { RedisClient.Add <T>(key, value, expire); } }
public bool Save(string key, GetFinancialDataSourcesResponse response) { var cachedData = _client.Get <GetFinancialDataSourcesResponse>(key); if (cachedData == null) { var expireInTimespan = new TimeSpan(1, 0, 0, 0); _client.Add(key, response, expireInTimespan); return(true); } else { return(false); } }
public void DyanmoDb_ExerciseCacheClient() { // Expecting the Set operation to succeed bool setResponse = _client.Set <DummyObject>(_itemCacheKey, _item); Assert.AreEqual(true, setResponse); // Expecting the Get to return the item cached above var actual = _client.Get <DummyObject>(_itemCacheKey); Assert.IsNotNull(actual); Assert.AreEqual(_item.UserId, actual.UserId); // Expecting Add to return false since the item is already cached bool addResponse = _client.Add <DummyObject>(_itemCacheKey, _item); Assert.AreEqual(false, addResponse); // Expecting remove to succeed bool removeResponse = _client.Remove(_itemCacheKey); Assert.AreEqual(true, removeResponse); // Add the item back, expecting success addResponse = _client.Add <DummyObject>(_itemCacheKey, _item); Assert.AreEqual(true, addResponse); // Remove it again removeResponse = _client.Remove(_itemCacheKey); // Clear the counter if it exists removeResponse = _client.Remove(_counterCacheKey); // Initialize the counter, incResponse should be equal to 0 since the counter doesn't exist long incResponse = _client.Increment(_counterCacheKey, 0); // Increment by 1 long updatedIncResponse = _client.Increment(_counterCacheKey, 1); Assert.AreEqual(incResponse + 1, updatedIncResponse); // Decrement by 1 long decResponse = _client.Decrement(_counterCacheKey, 1); Assert.AreEqual(incResponse, decResponse); // Clear out the cache - this will cause a very long delete/re-create DynamoDB table sequence _client.FlushAll(); }
/// <summary> /// Save item to cache /// </summary> /// <typeparam name="T">Type of object in cache</typeparam> /// <param name="key">cache key</param> /// <param name="value">object to save</param> /// <param name="expiresIn">Length of time object should live in cache</param> /// <returns>Boolean indicating whether save was successful</returns> public bool Set <T>(string key, T value, TimeSpan expiresIn) { if (!CacheEnabled) { return(false); } try { if (value != null) { _client.Add(key, value, expiresIn); return(true); } else { return(Delete(key)); } } catch (Exception ex) { //don't let cache failures kill the whole app. best to log here, and continue on _log.Error(string.Format("Error setting cache: {0}", ex)); return(false); } }
public static void AddCache <T>(this T obj, ICacheClient cache) where T : class, IHasGuidId { var key = UrnId.Create <T>(obj.Id); var wrapper = obj.Wrap(); cache.Add(key, wrapper.ToJson()); }
public void Seed() { var dummy = new Dummy() { Id = "bob", Message = "Writes all the data here." }; _client.Add <Dummy>(dummy.Id, dummy); }
public override void Set(string key, object value, TimeSpan?slidingExpireTime = null, TimeSpan?absoluteExpireTime = null) { if (value == null) { throw new StoveException("Can not insert null values to the cache!"); } _cacheClient.Add(GetLocalizedKey(key), value, absoluteExpireTime ?? slidingExpireTime ?? DefaultAbsoluteExpireTime ?? DefaultSlidingExpireTime); }
public void Set(string key, object value, int cacheTime = 60) { if (null == value) { return; } client.Add(key, value, new TimeSpan(0, cacheTime, 0)); }
public void Add(string key, object data, int cacheTime) { if (data == null) { return; } _database.Add(key, data, DateTimeOffset.Now.AddMinutes(cacheTime)); }
public IActionResult Add([FromBody] Content newEntry) { ICacheClient client = getCacheClient(); bool added = client.Add("content_" + newEntry.Id.ToString(), newEntry, DateTimeOffset.Now.AddMinutes(10)); if (!added) { return(BadRequest("Cache error")); } return(Ok()); }
public IActionResult Index() { ICacheClient client = getCacheClient(); Content content = new Content() { Id = 5, Text = "this is a bunch of text that we want to store" }; bool added = client.Add("content_" + content.Id.ToString(), content, DateTimeOffset.Now.AddMinutes(1)); return(View()); }
public IActionResult Add([FromBody] Widget newEntry) { ICacheClient client = getCacheClient(); // this also does an upsert. bool added = client.Add("widget_" + newEntry.Id.ToString(), newEntry, DateTimeOffset.Now.AddMinutes(10)); if (!added) { return(BadRequest("Cache error")); } return(Ok()); }
public static async Task <R.Responses_Query <TResponse> > ToOptimizedCachedResult <TResponse>(this IRequest request, Q.Queries_Query <TResponse> query, ICacheClient cache, Func <Task <R.Responses_Query <TResponse> > > factory) { var key = query.GetCacheKey(); var cached = cache.Get <R.Responses_Query <TResponse> >(key); if (cached == null) { cached = await factory(); cache.Add(key, cached); } return(cached); }
public bool Add <T>(T data) { if (data == null || !IsCachingServer) { return(false); } try { PropertyInfo[] properties = typeof(T).GetProperties(); var key = Helper.GetClassName <T>() + ":" + properties[0].GetValue(data).ToString(); Tuple.Create(key, data); //Find key if (Sut.Exists(key)) { if (Sut.Remove(key)) { LogManager.Logger.LogError(new Exception("Error when remove object " + Helper.GetClassName <T>() + "- Key: " + key)); return(false); } } //Add if (TimeExpried > 0) { return(Sut.Add(key, data, TimeSpan.FromMinutes(TimeExpried))); } else { return(Sut.Add(key, data)); } } catch (Exception ex) { LogManager.Logger.LogError(ex); return(false); } }
public T AddOrGetExisting <T>(string key, Func <T> valueFactory, int expirationSeconds = 0) { T value = default(T); try { value = _redisClient.Get <T>(key); } catch { return(valueFactory()); } if (value == null) { value = valueFactory(); try { if (expirationSeconds > 0) { _redisClient.Add(key, value, new TimeSpan(0, 0, expirationSeconds)); } else { _redisClient.Add(key, value); } } catch { } return(value); } return(value); }
public static async Task <R.Responses_Paged <TResponse> > ToOptimizedCachedAndSubscribedPagedResult <TResponse>(this IRequest request, Q.Queries_Paged <TResponse> query, ICacheClient cache, ISubscriptionManager manager, Func <Task <R.Responses_Paged <TResponse> > > factory) { var key = query.GetCacheKey(); var cached = cache.Get <R.Responses_Paged <TResponse> >(key); if (cached == null) { cached = await factory(); cache.Add(key, cached); } manager.SubscribeWith(cached, query, request.GetSessionId()); return(cached); }
public List <RegressionUnit> GetForecast(DateTime date, string model, string key) { List <RegressionUnit> forecast = null; //var serializer = new NewtonsoftSerializer(); //var cacheClient = new StackExchangeRedisCacheClient(serializer); var cacheForecast = stackCache.Get <List <RegressionUnit> >(key); if (cacheForecast == null) { StocksData sd = new StocksData(); forecast = sd.Forecast(date, model); stackCache.Add(key, forecast, DateTimeOffset.Now.AddHours(1)); return(forecast); } return(cacheForecast); }
public IActionResult Seed(int num, int start) { ICacheClient client = getCacheClient(); for (int idx = start; idx < start + num; idx++) { Content newEntry = new Content() { Id = idx, Text = string.Format("this is content for ID {0}", idx), }; bool added = client.Add("content_" + newEntry.Id.ToString(), newEntry, DateTimeOffset.Now.AddMinutes(10)); if (!added) { return(BadRequest("Cache error")); } } return(Ok()); }
public IActionResult Seed(int num, int start) { ICacheClient client = getCacheClient(); for (int idx = start; idx < start + num; idx++) { Widget newWidget = new Widget() { Id = idx, Name = string.Format("Widget {0}", idx), Price = (decimal)(idx + 1.5m) }; bool added = client.Add("widget_" + newWidget.Id.ToString(), newWidget, DateTimeOffset.Now.AddMinutes(10)); if (!added) { return(BadRequest("Cache error")); } } return(Ok()); }
public ResultMessage <bool> login(LoginRequestDto request) { var response = new ResultMessage <bool>() { err_code = 400, err_msg = "用户名或密码错误", }; return(Logger("登录接口", () => { var obj = _userRep.Find(r => r.Name == request.user_name && r.Pw == request.pw).FirstOrDefault(); if (obj != null) { #region 加入redis var cacheId = Guid.NewGuid().ToString().Replace("-", ""); var token = HashHelper.GetMd5ForUTF8(cacheId.ToString()); var userInfo = new UserInfoRedis { CacheId = token, name = obj.Name, date_time = DateTime.UtcNow.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss") }; var expiresDate = DateTime.Now.Date.AddDays(1); var expiresTime = expiresDate - DateTime.Now; _cacheClient.Add(userInfo); #endregion response.body = true; response.err_code = 200; response.err_msg = "登录成功"; } return response; }, ErrorHandles.Continue, LogModes.Error, ex => { return response; })); }
public IActionResult SeedBigData(int Id, int numBytes) { StringBuilder sb = new StringBuilder(numBytes); for (int idx = 0; idx < numBytes; idx++) { sb.Append('i'); } ICacheClient client = getCacheClient(); Content newEntry = new Content() { Id = Id, Text = sb.ToString(), }; bool added = client.Add("content_" + newEntry.Id.ToString(), newEntry, DateTimeOffset.Now.AddMinutes(10)); if (!added) { return(BadRequest("Cache error")); } return(Ok()); }
public IActionResult SeedBigData(int Id, int numBytes) { StringBuilder sb = new StringBuilder(numBytes); for (int idx = 0; idx < numBytes; idx++) { sb.Append('i'); } ICacheClient client = getCacheClient(); Widget bigDataWidget = new Widget() { Id = Id, Name = sb.ToString(), Price = 5m }; bool added = client.Add("widget_" + bigDataWidget.Id.ToString(), bigDataWidget, DateTimeOffset.Now.AddMinutes(10)); if (!added) { return(BadRequest("Cache error")); } return(Ok()); }
public static void AddCache <T>(this Wrapper <T> wrapper, ICacheClient cache, string key) where T : class, IHasGuidId { cache.Add(key, wrapper.ToJson()); }
public bool Add <T>(string key, T value) { return(cache.Add(prefix + key, value)); }
public T Add(CacheItem <T> item) { client.Add(keyPrefix + item.Key, item.Value, item.Duration); return(item.Value); }
public override void Set <T>(string key, T value, int duration) { _redisCacheClient.Add <T>(key, value, TimeSpan.FromMinutes(duration)); }