public void Add(string key, object data, int duration) { _distributedCache.Set(key, CacheSerializer.Serialize(data), new DistributedCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddMinutes(duration) }); }
public void ShouldSerializeCacheToJson() { var testDictionary = new Dictionary <string, int>(); testDictionary[SerieName] = SerieId; var cacheSerializer = new CacheSerializer(); string serializedContents = cacheSerializer.Serialize(testDictionary); Assert.That(serializedContents, Is.EqualTo(CreateJsonString())); }
private async Task <IReadOnlyList <IWallet> > ReloadAllAsync(string walletId) { var result = (await _repository.GetAsync(walletId)).Select(CachedWalletModel.Create).ToArray(); try { await _redisDatabase.HashSetAsync( GetCacheKey(walletId), result.Select(x => new HashEntry(x.AssetId, CacheSerializer.Serialize(x))).ToArray()); await _redisDatabase.KeyExpireAsync(GetCacheKey(walletId), _cacheExpiration); } catch (RedisConnectionException ex) { _log.Warning("Redis cache is not available", ex); } return(result); }
public T Get(string cacheKeyName, int cacheTimeOutSeconds, Func <T> func) { //var redisManager = new PooledRedisClientManager("localhost:6379"); var redisCacheServer = ConfigurationManager.AppSettings["RedisCacheServer"]; var redisCacheServerPort = ConfigurationManager.AppSettings["RedisCacheServerPort"]; if (string.IsNullOrEmpty(redisCacheServer)) { throw new ApplicationException("RedisCacheServer must be defined in appsettings"); } if (string.IsNullOrEmpty(redisCacheServerPort)) { throw new ApplicationException("RedisCacheServerPort must be defined in appsettings"); } var redisKey = ConfigurationManager.AppSettings["RedisCacheServerKey"]; string connectionString; if (!string.IsNullOrEmpty(redisKey)) { connectionString = $"{redisCacheServer}:{redisCacheServerPort},abortConnect=false,ssl=false,password={redisKey}"; } else { connectionString = $"{redisCacheServer}:{redisCacheServerPort}"; } using (var connectionMultiplexer = ConnectionMultiplexer.Connect(connectionString)) { lock (Locker) { redis = connectionMultiplexer.GetDatabase(); } var o = CacheSerializer.Deserialize <T>(redis.StringGet(cacheKeyName)); if (o != null) { return(o); } lock (Locker) { // get lock but release if it takes more than 60 seconds to complete to avoid deadlock if this app crashes before release //using (redis.AcquireLock(cacheKeyName + "-lock", TimeSpan.FromSeconds(60))) var lockKey = cacheKeyName + "-lock"; if (redis.LockTake(lockKey, Environment.MachineName, TimeSpan.FromSeconds(10))) { try { o = CacheSerializer.Deserialize <T>(redis.StringGet(cacheKeyName)); if (o == null) { o = func(); redis.StringSet(cacheKeyName, CacheSerializer.Serialize(o), TimeSpan.FromSeconds(cacheTimeOutSeconds)); } redis.LockRelease(lockKey, Environment.MachineName); return(o); } finally { redis.LockRelease(lockKey, Environment.MachineName); } } return(o); } } }