示例#1
0
        private TimeSpan GetAbsoluteExpiration(CacheExpiration cacheExpiration)
        {
            TimeSpan timeSpan;

            switch (cacheExpiration)
            {
            case CacheExpiration.HalfAnHour:
                timeSpan = TimeSpan.FromMinutes(30);
                break;

            case CacheExpiration.OneHour:
                timeSpan = TimeSpan.FromHours(1);
                break;

            case CacheExpiration.FourHours:
                timeSpan = TimeSpan.FromHours(4);
                break;

            case CacheExpiration.OneDay:
                timeSpan = TimeSpan.FromDays(1);
                break;

            case CacheExpiration.OneWeek:
                timeSpan = TimeSpan.FromDays(7);
                break;

            default:
                timeSpan = TimeSpan.Zero;
                break;
            }

            return(timeSpan);
        }
示例#2
0
        public Task SetAsync <T>(string key, T value, CacheExpiration expiration, CancellationToken cancelToken)
        {
            var min      = _cacheSettings.GetMinutes(expiration);
            var dateTime = DateTime.UtcNow.AddMinutes(min);

            return(SetAsync(key, value, dateTime, null, cancelToken));
        }
示例#3
0
 public SearchTemplateRepository(string clusterUrl, string index, ISimpleCache <SearchTemplate> cache, CacheExpiration expiration)
 {
     _es         = new ElasticsearchClient(clusterUrl);
     _index      = index;
     _cache      = cache;
     _expiration = expiration;
 }
示例#4
0
        /// <summary>
        /// Sets the specified cached value
        /// </summary>
        public CachedValue<T> Set<T>(string key, string region, T value, CacheExpiration cacheExpiration)
        {
            DateTime now = DateTime.UtcNow;
            string k = GetCacheKey(key, region);
            if (MemoryCache.Get(k) is MemoryStorage storage)
            {
                storage.Version++;
                storage.LastValidatedDate = now;
                storage.CacheDate = now;
                storage.Value = value;
            }
            else
            {
                storage = new MemoryStorage
                {
                    CacheDate = now,
                    LastValidatedDate = now,
                    Version = 0L,
                    Value = value
                };

                var options = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = cacheExpiration?.SlidingExpiration };
                MemoryCache.Set(k, storage, options);
            }

            return storage.ToCachedValue<T>();
        }
        /// <summary>
        /// Sets the specified cached value
        /// </summary>
        public virtual CachedValue <T> Set <T>(string key, string region, T value, CacheExpiration cacheExpiration)
        {
            DateTime now = DateTime.UtcNow;
            string   k   = GetCacheKey(key, region);

            var newStorage = new Storage
            {
                CacheDate         = now,
                LastAccessedDate  = now,
                LastValidatedDate = now,
                Expiration        = cacheExpiration,
                Value             = value,
                Version           = 0L,
            };

            Func <string, Storage, Storage> updateIfExists = (newKey, existing) =>
            {
                existing.Version           = existing.Version + 1L;
                existing.LastValidatedDate = now;
                existing.LastAccessedDate  = now;
                existing.Value             = value;
                return(existing);
            };

            Storage storage = Dictionary.AddOrUpdate(k, newStorage, updateIfExists);

            return(storage.ToCachedValue <T>());
        }
示例#6
0
        private Storage SetRedis(string key, string region, object value, CacheExpiration expiration)
        {
            try
            {
                RedisKey redisKey        = MakeKey(key, region);
                string   serializedValue = SerializeObjectToCacheInRedis(value);
                DateTime now             = DateTime.UtcNow;
                var      hashEntries     = new[] {
                    new HashEntry(Hashes.CachedDateTicks, now.Ticks),
                    new HashEntry(Hashes.LastValidatedDateTicks, -1L),
                    new HashEntry(Hashes.SlidingExpirationTicks, expiration.SlidingExpiration == null? -1L : expiration.SlidingExpiration.Value.Ticks),
                    new HashEntry(Hashes.Value, serializedValue)
                };

                IDatabase    database       = Redis.GetDatabase();
                ITransaction setTransaction = database.CreateTransaction();
                setTransaction.HashSetAsync(redisKey, hashEntries);
                setTransaction.KeyExpireAsync(redisKey, now + expiration.SlidingExpiration);
                Task <long> versionTask = setTransaction.HashIncrementAsync(redisKey, Hashes.Version);

                setTransaction.Execute();

                long version = versionTask.Result - 1L;

                return(new Storage {
                    CachedDate = now, LastValidatedDate = now, SerializedValue = serializedValue, Version = version
                });
            }
            catch (StackExchange.Redis.RedisException x)
            {
                throw ExceptionFactory.CachingFailed(CacheOperation.Set, x);
            }
        }
        private void ExpireCache(CacheExpiration key)
        {
            _context.ExpiredCacheKeys
            .Add(key.ToEntity());

            _context.SaveChanges();
        }
示例#8
0
 public SearchTemplateRepository(CacheExpiration expiration)
 {
     _es         = new ElasticsearchClient(DEFAULT_CLUSTER);
     _index      = DEFAULT_INDEX;
     _cache      = new SearchTemplateCache(CleanupFireAndForget);
     _expiration = expiration;
 }
示例#9
0
        protected virtual async Task <T> AddToCache <T>(string key, CacheExpiration cacheExpiration, Func <Task <T> > getData)
        {
            await semaphore.WaitAsync();

            try
            {
                T data;
                if (GetFromCache(key, out data))
                {
                    return(data);
                }

                data = await getData();

                if (IsDataValid(data))
                {
                    memoryCache.Set(key, data, GetAbsoluteExpiration(cacheExpiration));
                }

                return(data);
            }
            finally
            {
                semaphore.Release();
            }
        }
示例#10
0
        /// <summary>
        /// Sets the specified cached value
        /// </summary>
        public CachedValue <T> Set <T>(string key, string region, T value, CacheExpiration cacheExpiration)
        {
            DateTime now = DateTime.UtcNow;
            string   k   = GetCacheKey(key, region);

            if (MemoryCache.Get(k) is Storage storage)
            {
                storage.Version++;
                storage.LastValidatedDate = now;
                storage.CacheDate         = now;
                storage.Value             = value;
            }
            else
            {
                storage = new Storage
                {
                    CacheDate         = now,
                    LastValidatedDate = now,
                    Value             = value,
                    Version           = 0L
                };

                var cachePolicy = new CacheItemPolicy();
                if (cacheExpiration?.SlidingExpiration != null)
                {
                    cachePolicy.SlidingExpiration = cacheExpiration.SlidingExpiration.GetValueOrDefault();
                }

                MemoryCache.Add(k, storage, cachePolicy);
            }

            return(storage.ToCachedValue <T>());
        }
示例#11
0
 private TimeSpan GetCacheExpiration()
 {
     if (CoreBaseSettings.Standalone && CacheExpiration < STANDALONE_CACHE_EXPIRATION)
     {
         CacheExpiration = CacheExpiration.Add(TimeSpan.FromSeconds(30));
     }
     return(CacheExpiration);
 }
示例#12
0
 public Task <T> GetOrSetAsync <T>(string key, Func <Task <T> > loader, CacheExpiration expiration, CancellationToken cancelToken)
 {
     return(GetOrSetAsync(key, loader, v =>
     {
         var min = _cacheSettings.GetMinutes(expiration);
         return DateTime.UtcNow.AddMinutes(min);
     }, null, cancelToken));
 }
示例#13
0
        public virtual async Task <T> GetOrCreate <T>(string key, CacheExpiration cacheExpiration, Func <Task <T> > getData)
        {
            if (GetFromCache(key, out T data))
            {
                return(data);
            }

            return(await AddToCache(key, cacheExpiration, getData));
        }
示例#14
0
 public CacheAttribute(
     int ttl,
     CacheExpiration expiration,
     params string[] cacheKeyProperties)
 {
     TTL = ttl;
     CacheKeyProperties = new HashSet <string>(cacheKeyProperties);
     CacheExpiration    = expiration;
 }
 public static ExpiredCacheKey ToEntity(this CacheExpiration model)
 {
     return(model == null? null:
            new ExpiredCacheKey
     {
         JsonCacheKey = JsonConvert.SerializeObject(model.CacheKey),
         UtcExpiration = model.Expiration.ToUniversalTime()
     });
 }
示例#16
0
        /// <summary>
        /// 存储Session对象
        /// </summary>
        /// <param name="sessionObject">session对象</param>
        /// <returns></returns>
        public static async Task StoreSessionAsync(AuthSession sessionObject)
        {
            if (sessionObject == null)
            {
                throw new ArgumentNullException(nameof(sessionObject));
            }
            string subjectId = sessionObject.GetSubjectId();

            if (string.IsNullOrWhiteSpace(subjectId))
            {
                throw new Exception("authentication subject is null or empty");
            }
            string sessionId = sessionObject.SessionId;

            if (string.IsNullOrWhiteSpace(sessionId))
            {
                throw new Exception("session key is null or empty");
            }
            var sessionConfig = SessionConfiguration.GetSessionConfiguration();
            var nowDate       = DateTimeOffset.Now;
            var expiresDate   = nowDate.Add(sessionConfig.Expires);

            sessionObject.Expires = expiresDate;
            var expiresSeconds = Convert.ToInt64((expiresDate - nowDate).TotalSeconds);
            var expiration     = new CacheExpiration()
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(expiresSeconds),
                SlidingExpiration = true
            };
            await CacheManager.String.SetAsync(new StringSetOptions()
            {
                CacheObject = GetCacheObject(),
                Items       = new List <CacheEntry>()
                {
                    new CacheEntry()
                    {
                        Key        = sessionId,
                        Value      = subjectId,
                        When       = CacheSetWhen.Always,
                        Expiration = expiration
                    },
                    new CacheEntry()
                    {
                        Key        = subjectId,
                        Value      = JsonSerializeHelper.ObjectToJson(sessionObject),
                        Expiration = expiration,
                        When       = CacheSetWhen.Always
                    }
                }
            }).ConfigureAwait(false);
        }
示例#17
0
        public void Set(string key, SearchTemplate value, CacheExpiration expiration)
        {
            var policy = new CacheItemPolicy();

            if (expiration.Type == ExpirationType.Sliding)
            {
                policy.SlidingExpiration = TimeSpan.FromMilliseconds(expiration.Milliseconds);
            }
            else
            {
                policy.AbsoluteExpiration = new DateTimeOffset().AddMilliseconds(expiration.Milliseconds);
            }

            _cache.Set(key, value, policy);
        }
示例#18
0
        /// <summary>
        /// Determines the expiration date of a cached item.
        /// </summary>
        /// <param name="expiration"></param>
        /// <returns></returns>
        private static DateTime GetExpiration(CacheExpiration expiration)
        {
            switch (expiration)
            {
            case CacheExpiration.OneMinute:
                return(DateTime.UtcNow.AddMinutes(1));

            case CacheExpiration.FifteenMinutes:
                return(DateTime.UtcNow.AddMinutes(15));

            case CacheExpiration.OneHour:
                return(DateTime.UtcNow.AddHours(1));

            case CacheExpiration.FourHours:
                return(DateTime.UtcNow.AddHours(4));

            default:
                return(DateTime.UtcNow);
            }
        }
示例#19
0
 /// <summary>
 /// Get key expiration
 /// </summary>
 /// <param name="expiration">Cache expiration</param>
 /// <returns></returns>
 internal static Tuple <bool, TimeSpan?> GetExpiration(CacheExpiration expiration)
 {
     if (expiration == null)
     {
         return(new Tuple <bool, TimeSpan?>(false, null));
     }
     if (expiration.SlidingExpiration)
     {
         return(new Tuple <bool, TimeSpan?>(true, expiration.AbsoluteExpirationRelativeToNow));
     }
     else if (expiration.AbsoluteExpiration.HasValue)
     {
         var nowDate = DateTimeOffset.Now;
         if (expiration.AbsoluteExpiration.Value <= nowDate)
         {
             return(new Tuple <bool, TimeSpan?>(false, TimeSpan.Zero));
         }
         return(new Tuple <bool, TimeSpan?>(false, expiration.AbsoluteExpiration.Value - nowDate));
     }
     return(new Tuple <bool, TimeSpan?>(false, null));
 }
示例#20
0
        /// <summary>
        /// Set cache
        /// </summary>
        /// <param name="key">Cache key</param>
        /// <param name="data">Cache objects</param>
        /// <param name="cacheTime">Cache time</param>
        /// <param name="expiration">Cache type</param>
        public void Set(string key, object data, int cacheTime, CacheExpiration expiration)
        {
            if (data == null)
            {
                return;
            }

            var policy = new CacheItemPolicy();

            if (cacheTime > 0)
            {
                if (expiration == CacheExpiration.Absolute)
                {
                    policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
                }

                if (expiration == CacheExpiration.Sliding)
                {
                    policy.SlidingExpiration = TimeSpan.FromMinutes(cacheTime);
                }
            }

            _cache.Set(new CacheItem(key, data), policy);
        }
        /// <summary>
        /// Sets the specified cached value
        /// </summary>

        public CachedValue <T> Set <T>(string key, string region, T value, CacheExpiration cacheExpiration)
        {
            var    now = DateTime.UtcNow;
            string k   = GetCacheKey(key, region);

            DistributedStorage storage         = null;
            string             serializedValue = Serializer.Serialize(value);

            byte[] bytes = DistributedCache.Get(k);

            if (bytes == null)
            {
                storage = new DistributedStorage
                {
                    CacheDate         = now,
                    Version           = 0L,
                    Value             = serializedValue,
                    LastValidatedDate = now
                };
            }
            else
            {
                storage = DistributedStorage.FromBytes(Serializer, bytes);
                storage.Version++;
                storage.LastValidatedDate = now;
                storage.Value             = serializedValue;
            }

            var options = new DistributedCacheEntryOptions {
                AbsoluteExpirationRelativeToNow = cacheExpiration.SlidingExpiration
            };

            DistributedCache.Set(k, storage.ToBytes(Serializer), options);

            return(storage.ToCachedValue <T>(Serializer));
        }
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (UsersPath != null)
         {
             hashCode = hashCode * 59 + UsersPath.GetHashCode();
         }
         if (GroupsPath != null)
         {
             hashCode = hashCode * 59 + GroupsPath.GetHashCode();
         }
         if (SystemRelativePath != null)
         {
             hashCode = hashCode * 59 + SystemRelativePath.GetHashCode();
         }
         if (DefaultDepth != null)
         {
             hashCode = hashCode * 59 + DefaultDepth.GetHashCode();
         }
         if (ImportBehavior != null)
         {
             hashCode = hashCode * 59 + ImportBehavior.GetHashCode();
         }
         if (PasswordHashAlgorithm != null)
         {
             hashCode = hashCode * 59 + PasswordHashAlgorithm.GetHashCode();
         }
         if (PasswordHashIterations != null)
         {
             hashCode = hashCode * 59 + PasswordHashIterations.GetHashCode();
         }
         if (PasswordSaltSize != null)
         {
             hashCode = hashCode * 59 + PasswordSaltSize.GetHashCode();
         }
         if (OmitAdminPw != null)
         {
             hashCode = hashCode * 59 + OmitAdminPw.GetHashCode();
         }
         if (SupportAutoSave != null)
         {
             hashCode = hashCode * 59 + SupportAutoSave.GetHashCode();
         }
         if (PasswordMaxAge != null)
         {
             hashCode = hashCode * 59 + PasswordMaxAge.GetHashCode();
         }
         if (InitialPasswordChange != null)
         {
             hashCode = hashCode * 59 + InitialPasswordChange.GetHashCode();
         }
         if (PasswordHistorySize != null)
         {
             hashCode = hashCode * 59 + PasswordHistorySize.GetHashCode();
         }
         if (PasswordExpiryForAdmin != null)
         {
             hashCode = hashCode * 59 + PasswordExpiryForAdmin.GetHashCode();
         }
         if (CacheExpiration != null)
         {
             hashCode = hashCode * 59 + CacheExpiration.GetHashCode();
         }
         if (EnableRFC7613UsercaseMappedProfile != null)
         {
             hashCode = hashCode * 59 + EnableRFC7613UsercaseMappedProfile.GetHashCode();
         }
         return(hashCode);
     }
 }
        /// <summary>
        /// Returns true if OrgApacheJackrabbitOakSecurityUserUserConfigurationImplProperties instances are equal
        /// </summary>
        /// <param name="other">Instance of OrgApacheJackrabbitOakSecurityUserUserConfigurationImplProperties to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(OrgApacheJackrabbitOakSecurityUserUserConfigurationImplProperties other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     UsersPath == other.UsersPath ||
                     UsersPath != null &&
                     UsersPath.Equals(other.UsersPath)
                     ) &&
                 (
                     GroupsPath == other.GroupsPath ||
                     GroupsPath != null &&
                     GroupsPath.Equals(other.GroupsPath)
                 ) &&
                 (
                     SystemRelativePath == other.SystemRelativePath ||
                     SystemRelativePath != null &&
                     SystemRelativePath.Equals(other.SystemRelativePath)
                 ) &&
                 (
                     DefaultDepth == other.DefaultDepth ||
                     DefaultDepth != null &&
                     DefaultDepth.Equals(other.DefaultDepth)
                 ) &&
                 (
                     ImportBehavior == other.ImportBehavior ||
                     ImportBehavior != null &&
                     ImportBehavior.Equals(other.ImportBehavior)
                 ) &&
                 (
                     PasswordHashAlgorithm == other.PasswordHashAlgorithm ||
                     PasswordHashAlgorithm != null &&
                     PasswordHashAlgorithm.Equals(other.PasswordHashAlgorithm)
                 ) &&
                 (
                     PasswordHashIterations == other.PasswordHashIterations ||
                     PasswordHashIterations != null &&
                     PasswordHashIterations.Equals(other.PasswordHashIterations)
                 ) &&
                 (
                     PasswordSaltSize == other.PasswordSaltSize ||
                     PasswordSaltSize != null &&
                     PasswordSaltSize.Equals(other.PasswordSaltSize)
                 ) &&
                 (
                     OmitAdminPw == other.OmitAdminPw ||
                     OmitAdminPw != null &&
                     OmitAdminPw.Equals(other.OmitAdminPw)
                 ) &&
                 (
                     SupportAutoSave == other.SupportAutoSave ||
                     SupportAutoSave != null &&
                     SupportAutoSave.Equals(other.SupportAutoSave)
                 ) &&
                 (
                     PasswordMaxAge == other.PasswordMaxAge ||
                     PasswordMaxAge != null &&
                     PasswordMaxAge.Equals(other.PasswordMaxAge)
                 ) &&
                 (
                     InitialPasswordChange == other.InitialPasswordChange ||
                     InitialPasswordChange != null &&
                     InitialPasswordChange.Equals(other.InitialPasswordChange)
                 ) &&
                 (
                     PasswordHistorySize == other.PasswordHistorySize ||
                     PasswordHistorySize != null &&
                     PasswordHistorySize.Equals(other.PasswordHistorySize)
                 ) &&
                 (
                     PasswordExpiryForAdmin == other.PasswordExpiryForAdmin ||
                     PasswordExpiryForAdmin != null &&
                     PasswordExpiryForAdmin.Equals(other.PasswordExpiryForAdmin)
                 ) &&
                 (
                     CacheExpiration == other.CacheExpiration ||
                     CacheExpiration != null &&
                     CacheExpiration.Equals(other.CacheExpiration)
                 ) &&
                 (
                     EnableRFC7613UsercaseMappedProfile == other.EnableRFC7613UsercaseMappedProfile ||
                     EnableRFC7613UsercaseMappedProfile != null &&
                     EnableRFC7613UsercaseMappedProfile.Equals(other.EnableRFC7613UsercaseMappedProfile)
                 ));
        }
示例#24
0
 /// <summary>
 /// Writes an item into the cache.
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="key"></param>
 /// <param name="expiration"></param>
 public static void Write(string key, object obj, CacheExpiration expiration)
 {
     HttpContext.Current.Cache.Insert(key, obj, null, GetExpiration(expiration), System.Web.Caching.Cache.NoSlidingExpiration);
 }
示例#25
0
        public static Response <TCacheItem> GetCachedWithCustomQuery <TCacheItem>(this ICacheProvider cacheProvider, string key, Func <Response <TCacheItem> > acquire, int cacheMinutes = 60, CacheExpiration cacheExpiration = CacheExpiration.SlidingExpiration)
        {
            var response = new Response <TCacheItem>();
            var item     = cacheProvider.Get <TCacheItem>(key);

            if (item != null)
            {
                response.Payload = item;
                return(response);
            }

            var acquireResponse = acquire();

            response.Merge(acquireResponse);

            if (response.NotOk)
            {
                return(response);
            }

            if (cacheMinutes > 0)
            {
                cacheProvider.Insert(key, acquireResponse.Payload, cacheMinutes * 60, cacheExpiration);
            }

            response.Payload = acquireResponse.Payload;
            return(response);
        }
示例#26
0
 private void OnCacheExpiration()
 {
     CacheExpiration?.Invoke();
 }
示例#27
0
        public static TCacheItem GetCached <TCacheItem>(this ICacheProvider cacheProvider, string key, Func <TCacheItem> acquire, int cacheMinutes = 60, CacheExpiration cacheExpiration = CacheExpiration.SlidingExpiration)
        {
            var item = cacheProvider.Get <TCacheItem>(key);

            if (item != null)
            {
                return(item);
            }

            var result = acquire();

            if (cacheMinutes > 0 && result != null)
            {
                cacheProvider.Insert(key, result, cacheMinutes * 60, cacheExpiration);
            }

            return(result);
        }
 public int GetMinutes(CacheExpiration expiration)
 {
     return((int)expiration);
 }
示例#29
0
        /// <summary>
        /// Get or set by type.
        /// Cache key is automagically created from object type and identify.
        /// Cache absolute expiration is taken from the enum value or override by application configuration.
        /// Example: repo.GetOrSetByType{User}(1, LoadUserByIdFromDb(1)); // Get or load and set User 1
        /// </summary>
        /// <typeparam name="T">Type of cached object</typeparam>
        /// <param name="repo">ICacheRepository</param>
        /// <param name="identifier">Type specific unique identify for object</param>
        /// <param name="loader">Delegate to invoke if cached item is not found</param>
        /// <param name="expiration">Abosolute expiration to use if object is loaded and cached</param>
        /// <returns>Cached object or result of loader</returns>
        public static T GetOrSetByType <T>(this ICacheRepository repo, object identifier, Func <T> loader, CacheExpiration expiration)
        {
            var key = AsyncCacheRepositoryExtensions.CreateKey <T>(identifier);

            return(repo.GetOrSet(key, loader, expiration));
        }
示例#30
0
        /// <summary>
        /// Set by type.
        /// Cache key is automagically created from object type and identify.
        /// Cache absolute expiration is taken from the enum value or override by application configuration.
        /// Example: repo.SetByType{User}(1, user); // Set user by their Id
        /// </summary>
        /// <typeparam name="T">Type of cached object</typeparam>
        /// <param name="repo">ICacheRepository</param>
        /// <param name="identifier">Type specific unique identify for object</param>
        /// <param name="expiration">Abosolute expiration to use for cache</param>
        /// <param name="value">Object to be cached</param>
        public static void SetByType <T>(this ICacheRepository repo, object identifier, T value, CacheExpiration expiration)
        {
            var key = AsyncCacheRepositoryExtensions.CreateKey <T>(identifier);

            repo.Set(key, value, expiration);
        }