示例#1
0
        /// <summary>
        ///     Get a cached item. If it's not in the cache yet, then load and cache it
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="cacheManager">Cache manager</param>
        /// <param name="key">Cache key</param>
        /// <param name="cacheTime">Cache time in minutes (0 - do not cache)</param>
        /// <param name="acquire">Function to load item if it's not in the cache yet</param>
        /// <returns>Cached item</returns>
        public static T Get <T>(this IRedisCacheService cacheManager, string key, int cacheTime, Func <T> acquire)
        {
            //item already is in cache, so return it
            if (cacheManager.IsSet(key))
            {
                return(cacheManager.Get <T>(key));
            }

            //or create it using passed function
            var result = acquire();

            //and set in cache (if cache time is defined)
            if (cacheTime > 0)
            {
                cacheManager.Set(key, result, DateTime.Now.AddMinutes(cacheTime));
            }

            return(result);
        }