C#个人珍藏基础类库分享 — 2、Memcached缓存帮助类MemcachedHelper

        做.NET后台开发的同学,对缓存处理一定不陌生,这里把我混迹C#圈子十余载珍藏的基础类库分享出来,希望能够给刚踏入开发门槛的朋友一些帮助。

        后续我会逐步分享基础库的其余部分,先列个大纲:

C#个人珍藏基础类库分享 — 1、通用缓存帮助类CacheHelper

C#个人珍藏基础类库分享 — 2、Memcached缓存帮助类MemcachedHelper

C#个人珍藏基础类库分享 — 3、目录、文件帮助类FileHelper

C#个人珍藏基础类库分享 — 4、字节数组帮助类BytesObjectHelper

C#个人珍藏基础类库分享 — 5、日志帮助类LogHelper

C#个人珍藏基础类库分享 — 6、数据库处理帮助类SqlHelper

C#个人珍藏基础类库分享 — 7、Xml处理帮助类XmlHelper

C#个人珍藏基础类库分享 — 8、通用工具帮助类ToolHelper

        
首先还是科普一下概念:

Memcache  是一个高性能的分布式的内存对象缓存系统,通过在内存里维护一个统一的巨大的hash表,它能够用来存储各种格式的数据,包括图像、视频、文件以及数据库检索的结果等。简单的说就是将数据调用到内存中,然后从内存中读取,从而大大提高读取速度。

1、设置缓存的方法如下 :

        #region 设置缓存

        /// 
        /// 设置缓存
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 缓存键名
        /// 
        /// 异常时返回False
        public static bool SetCache(string serverList, string key, object val)
        {
            return SetCache(serverList, key, val, null, 0);
        }

        /// 
        /// 设置缓存
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 缓存键名
        /// 
        /// 
        /// 异常时返回False
        public static bool SetCache(string serverList, string key, object val, DateTime? expiry)
        {
            return SetCache(serverList, key, val, expiry, 0);
        }

        /// 
        /// 设置缓存
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 缓存键名
        /// 
        /// 
        /// 
        /// 异常时返回False
        public static bool SetCache(string serverList, string key, object val, DateTime? expiry, int hashCode)
        {
            try
            {
                MemcachedClient mc = GetMClient(serverList);

                if (!string.IsNullOrEmpty(key) && val != null && expiry != null && hashCode != 0)
                    return mc.Set(key, val, expiry.Value, hashCode);
                else if (!string.IsNullOrEmpty(key) && val != null && expiry != null)
                    return mc.Set(key, val, expiry.Value);
                else if (!string.IsNullOrEmpty(key) && val != null)
                    return mc.Set(key, val);
                else
                    throw new Exception("请确保参数正确(key,val)。");
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("MemcachedHelper").Error(null, ex);
                return false;
            }
        }

        #endregion

2、获取缓存:

       #region 获取缓存

        /// 
        /// 获取缓存。
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 缓存键名
        /// 异常时返回空值
        public static object GetCache(string serverList, string key)
        {
            return GetCache(serverList, key, 0, null);
        }

        /// 
        /// 获取缓存
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 缓存键名
        /// 
        /// 异常时返回空值
        public static object GetCache(string serverList, string key, int hashCode)
        {
            return GetCache(serverList, key, hashCode, null);
        }

        /// 
        /// 获取缓存
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 缓存键名
        /// 
        /// 
        /// 异常时返回空值
        public static object GetCache(string serverList, string key, int hashCode, bool? asString)
        {
            try
            {
                MemcachedClient mc = GetMClient(serverList);

                if (!string.IsNullOrEmpty(key) && hashCode != 0 && asString != null)
                    return mc.Get(key, hashCode, asString.Value);
                else if (!string.IsNullOrEmpty(key) && hashCode != 0)
                    return mc.Get(key, hashCode);
                else if (!string.IsNullOrEmpty(key))
                    return mc.Get(key);
                else
                    throw new Exception("请确保参数正确(key)。");
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("MemcachedHelper").Error(null, ex);
                return null;
            }
        }

        #endregion

3、删除缓存:

       #region 删除缓存

        /// 
        /// 删除缓存
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 缓存键名
        /// 异常时返回False
        public static bool DelCache(string serverList, string key)
        {
            return DelCache(serverList, key, null);
        }

        /// 
        /// 删除缓存
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 缓存键名
        /// 
        /// 异常时返回False
        public static bool DelCache(string serverList, string key, DateTime? expiry)
        {
            try
            {
                MemcachedClient mc = GetMClient(serverList);
                if (key != null && expiry != null)
                    return mc.Delete(key, expiry.Value);
                else if (key != null)
                    return mc.Delete(key);
                else
                    throw new Exception("请确保参数正确(key)。");
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("MemcachedHelper").Error(null, ex);
                return false;
            }
        }

        #endregion

4、其它操作:

       #region 其它操作

        /// 
        /// 清空服务器缓存
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 异常时返回False
        public static bool DelAllCache(string serverList)
        {
            try
            {
                MemcachedClient mc = GetMClient(serverList);
                return mc.FlushAll();
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("MemcachedHelper").Error(null, ex);
                return false;
            }
        }

        /// 
        /// 依据键名检查缓存是否存在
        /// 
        /// 缓存服务器列表,以逗号分隔,如:127.0.0.1:11210,192.168.1.2:11210
        /// 缓存键名
        /// 异常时返回False
        public static bool IsKeyExist(string serverList, string key)
        {
            try
            {
                MemcachedClient mc = GetMClient(serverList);
                return mc.KeyExists(key);
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("MemcachedHelper").Error(null, ex);
                return false;
            }
        }

        /// 
        /// 打印命中率
        /// 返回值为百分比,比如是51.2 就表示命中率是51.2%
        /// 
        /// 
        /// 异常时返回Null
        public Dictionary GetHits(string serverList)
        {
            try
            {
                Dictionary serverHits = new Dictionary();
                MemcachedClient mc = GetMClient(serverList);
                IDictionary stats = mc.Stats();
                foreach (string key1 in stats.Keys)
                {
                    Hashtable values = (Hashtable)stats[key1];
                    double getAll = 0;
                    double getHit = 0;
                    foreach (string key2 in values.Keys)
                    {
                        if (key2 == "cmd_get")
                            getAll = double.Parse(values[key2].ToString());
                        else if (key2 == "get_hits")
                            getHit = double.Parse(values[key2].ToString());
                    }
                    if (getAll > 0)
                        serverHits.Add(key1, Math.Round((getHit / getAll) * 100, 2));
                    else
                        serverHits.Add(key1, 0);
                }
                return serverHits;
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("MemcachedHelper").Error(null, ex);
                return null;
            }
        }

        #endregion

5、最后,给一个缓存应用实例

elem.TheData = GetData(cacheName);
if (elem.TheData == null || elem.TheData.Length <= 0)
{
    if (op == (int)OpType.Mobile)
    {
        cacheName = string.Format("znly_{0}_{1}_{2}_{3}_{4}_{5}_{6}", schemeId, SchemeBranchId, type, (int)OpType.Common, schemeType,sedn,page);
        elem.TheData = GetData(cacheName);
    }
    if (elem.TheData == null || elem.TheData.Length <= 0)
    {
        if (SchemeBranchId > 0)
        {
            elem = GetElemsetByOp(SchemeBranchId, type, ref op,schemeType,sedn,page);
        }
        else
        {
            elem = GetElemsetByOp(schemeId, type, ref op ,schemeType,sedn,page);
        }
        if (elem != null)
        {
            if (elem.TheData.Length > 0)
            {
                cacheName = string.Format("znly_{0}_{1}_{2}_{3}_{4}_{5}_{6}", schemeId, SchemeBranchId, type, op, schemeType, sedn,page);
                MemcachedHelper.SetCache(siteConfig.MemcachedList, cacheName, elem.TheData);
            }
        }
    }
}


    private byte[] GetData(string cacheName)
    {
        byte[] data = new byte[] { };
        if (MemcacheStatus == "1")
        {
            data = MemcachedHelper.GetCache(siteConfig.MemcachedList, cacheName) as byte[];
        }
        if (MemcacheStatus == "2")
        {
            Random rdm = new Random();
            int IntRdm = rdm.Next(0, 11);
            if (IntRdm > 5)
            {
                data = MemcachedHelper.GetCache(siteConfig.MemcachedList, cacheName) as byte[];
            }
        }
        return data;
    }

简单解析一下上面的方法:

1、通过GetData()获取cache内容

2、如果返回空,并且op == (int)OpType.Mobile,查找另一个缓存

3、如果elem.TheData == null || elem.TheData.Length <= 0,通过db查询结果

4、最后,通过SetCache把获得的数据更新到Memcache

你可能感兴趣的:(C#,分享,缓存,c#,数据库)