sitecore 缓存管理器


namespace XXX.Shared.Infrastructure.Caching
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Caching;
    using System.Threading;
    using Sitecore.Data;
    using Sitecore.Diagnostics;
    using Sitecore.Sites;

    /// <summary>
    ///     The cache manager.
    /// </summary>
    public sealed class CacheManager
    {
        #region Static Fields

        private static readonly Lazy<CacheManager> Instance = new Lazy<CacheManager>(() => new CacheManager(), LazyThreadSafetyMode.ExecutionAndPublication);

        private static readonly object SyncLock = new object();

        #endregion

        #region Fields

        private readonly ObjectCache cache = MemoryCache.Default;

        #endregion

        #region Public Properties

        /// <summary>
        ///     Gets the current.
        /// </summary>
        public static CacheManager Current
        {
            get { return Instance.Value; }
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// The add.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="expiryTimeInHours">
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        public void Add<T>(string key, T data, double expiryTimeInHours = 6) where T : class
        {
            try
            {
                if (data == null)
                {
                    throw new ArgumentNullException("data", "Cannot add null to the cache.");
                }

                lock (SyncLock)
                {
                    var policy = new CacheItemPolicy
                    {
                        AbsoluteExpiration = DateTime.Now.AddHours(expiryTimeInHours),
                        Priority = CacheItemPriority.Default,
                        SlidingExpiration = TimeSpan.Zero
                    };

                    this.cache.Add(key, data, policy);
                }
            }
            catch (Exception ex)
            {
                Log.Debug(ex.Message, this);
            }
        }

        /// <summary>
        /// The contains key.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public bool ContainsKey(string key)
        {
            lock (SyncLock)
            {
                return this.cache.Contains(key);
            }
        }

        /// <summary>
        /// The get.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        /// <returns>
        /// The <see cref="T"/>.
        /// </returns>
        public T Get<T>(string key) where T : class
        {
            lock (SyncLock)
            {
                return this.ContainsKey(key) ? this.cache.Get(key) as T : default(T);
            }
        }

        /// <summary>
        /// The get all cache keys.
        /// </summary>
        /// <returns>
        /// The <see cref="IEnumerable{T}"/>.
        /// </returns>
        public IEnumerable<string> GetAllCacheKeys()
        {
            return this.cache.Select(item => item.Key).ToList();
        }

        /// <summary>
        /// The purge.
        /// </summary>
        public void Purge()
        {
            lock (SyncLock)
            {
                var keys = this.cache.Select(item => item.Key);

                keys.ToList().ForEach(this.Remove);
            }
        }

        /// <summary>
        /// The remove.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        public void Remove(string key)
        {
            lock (SyncLock)
            {
                if (!this.ContainsKey(key))
                {
                    return;
                }

                this.cache.Remove(key);
            }
        }

        public void RemoveSitecoreItemCache(string id, string siteName)
        {
            if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(siteName))
            {
                using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext(siteName)))
                {
                    var db = SiteContext.Current.Database;

                    if (db != null)
                    {
                        db.Caches.ItemCache.RemoveItem(new ID(id));

                        db.Caches.DataCache.RemoveItemInformation(new ID(id));

                        db.Caches.StandardValuesCache.RemoveKeysContaining(id);
                    }
                }
            }
        }

        /// <summary>
        /// The remove by prefix.
        /// </summary>
        /// <param name="prefix">
        /// The prefix.
        /// </param>
        public void RemoveByPrefix(string prefix)
        {
            lock (SyncLock)
            {
                var keys = this.cache.Where(item => item.Key.IndexOf(prefix, StringComparison.OrdinalIgnoreCase) != -1);

                keys.ToList().ForEach(item => this.Remove(item.Key));
            }
        }

        #endregion
    }
}
原文地址:https://www.cnblogs.com/lindaWei/p/4172349.html