自动生成缓存Key值的CacheKeyHelper

    /// <summary>
    /// CacheKeyHelper
    /// </summary>
    public class CacheKeyHelper
    {
        /// <summary>
        /// 域名
        /// </summary>
        const string DomainName = "App";

        /// <summary>
        /// 当前类型
        /// </summary>
        private static readonly Type CurrentType = typeof (CacheKeyHelper);

        /// <summary>
        /// 获取缓存Key
        /// </summary>
        /// <param name="detailCacheKey">PartialCacheKey</param>
        /// <returns></returns>
        public static string GetCacheKey(string detailCacheKey)
        {
            MethodBase mb = GetCaller();
            if (mb != null && mb.DeclaringType != null)
            {
                return string.Format("{0}:{1}:{2}:{3}_{4}", DomainName, mb.DeclaringType.Namespace, mb.DeclaringType.Name, mb.Name, detailCacheKey.Md5());
            }

            return string.Format("{0}_{1}", DomainName, detailCacheKey.Md5());
        }

        /// <summary>
        /// 获取缓存Key
        /// </summary>
        /// <param name="reqObj">reqObj</param>
        /// <param name="properties">properties</param>
        /// <returns>PartialCacheKey</returns>
        public static string GetCacheKey<T>(T reqObj, IEnumerable<string> properties) where T : class
        {
            return GetCacheKey(string.Join("_", properties.Select(p => reqObj.GetPropertyValue(p, "null").ToString())));
        }

        /// <summary>
        /// 获取缓存Key
        /// </summary>
        /// <param name="reqObj">reqObj</param>
        /// <returns>PartialCacheKey</returns>
        public static string GetCacheKey<T>(T reqObj) where T : class
        {
            return GetCacheKey(reqObj, typeof(T).GetProperties().Where(p => p.CanRead).Select(q => q.Name));
        }

        /// <summary>
        /// 获得非本类的直接调用者
        /// </summary>
        /// <returns></returns>
        private static MethodBase GetCaller()
        {
            var ss = new StackTrace(false);
            var currentClass = ss.GetFrame(0).GetMethod().DeclaringType;  
            MethodBase mb = null;
            var level = 1;
            while (true)
            {
                //index:0为本身的方法;1为调用方法;2为其上上层,依次类推
                mb = ss.GetFrame(level).GetMethod();
                if (mb.DeclaringType == null)
                {
                    break;
                }

                if (mb.DeclaringType != CurrentType)
                {
                    break;
                }

                level++;
            }

            return mb;
        }
    }

 

posted @ 2017-10-10 09:46  zslm___  阅读(1630)  评论(0编辑  收藏  举报