.net 使用Memcached
1、创建个人MemcachedHelper类
/// <summary> /// 页 面 名:缓存管理类<br/> /// 说 明:设置、获取、移除Cache<br/> /// 作 者:xxx<br/> /// 时 间:2012-12-12(神奇的数字,传说中的12K)<br/> /// 修 改 者:<br/> /// 修改时间:<br/> ///</summary> public class MemcachedHelper { #region 变量和构造函数 //缓存服务器地址和端口,这样就实现了分布式缓存。服务器可以多个,多个时使用逗号(,)分开,用Socket读写数据"127.0.0.1:12345,127.0.0.2:12345", private static Dictionary<string, string> Servers = new Dictionary<string, string>(); static MemcachedClient mc = null; //服务器缓存 static Dictionary<string, SockIOPool> Servers1 = new Dictionary<string, SockIOPool>(); static object LOCK_OBJECT = new object();//安全锁定 /// <summary> /// 静态构造函数 /// </summary> static MemcachedHelper() { //初始化服务器列表 InitServer(); List<string> keys = Servers.Keys.ToList<string>(); foreach (var k in Servers.Keys) { SockIOPool pool = SockIOPool.GetInstance(k); string[] s = new string[] { Servers[k] }; pool.SetServers(s);//设置服务器 pool.MaxConnections = 10000; //最大连接数 pool.MinConnections = 10; //最小连接数 pool.SocketConnectTimeout = 1000; //Socket连接超时设置 pool.SocketTimeout = 100; // pool.HashingAlgorithm = HashingAlgorithm.NewCompatibleHash; //传输算法 pool.Initialize();//初始化缓存线程池 } //默认池 List<string> defaultServerList = new List<string>(); foreach (var k in Servers.Keys) { defaultServerList.Add(Servers[k]); } SockIOPool defaultPool = SockIOPool.GetInstance("DefaultPool"); defaultPool.SetServers(defaultServerList.ToArray());//设置服务器 defaultPool.MaxConnections = 10000; defaultPool.MinConnections = 10; defaultPool.SocketConnectTimeout = 1000; defaultPool.SocketTimeout = 100; defaultPool.Initialize(); //初始化默认线程池 mc = new MemcachedClient(); mc.PoolName = "DefaultPool"; } /// <summary> /// 初始化服务器列表,这里默认两台服务器. /// </summary> static void InitServer() { //这里可以写复杂灵活点,动态从配置文件获取,我这里固定了两个 Servers.Add("memservers", ConfigurationManager.AppSettings["memservers"]); // Servers.Add("Svr2", ConfigurationManager.AppSettings["Svr2"]); } private MemcachedHelper() { } #endregion #region 获取客户端,客户端使用单例模式生成 public static MemcachedClient GetClient(string server) { //MemcachedClient current = Singleton<MemcachedClient>.Instance; MemcachedClient current = Singleton<MemcachedClient>.GetInstance(); current.PoolName = server; return current; } #endregion #region 默认 #region 写(Set) /// <summary> /// 设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public static void Set(string key, object value) { mc.Set(key, value); } /// <summary> /// 设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="hashCode">哈希码</param> public static void Set(string key, object value, int hashCode) { mc.Set(key, value, hashCode); } /// <summary> /// 设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void Set(string key, object value, DateTime expiry) { mc.Set(key, value, expiry); } /// <summary> /// 设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void Set(string key, object value, DateTime expiry, int hashCode) { mc.Set(key, value, expiry, hashCode); } #endregion #region 读(Get) #region 返回泛型 /// <summary> /// 读取数据缓存 /// </summary> /// <param name="key">键</param> public static T Get<T>(string key) { return (T)mc.Get(key); } /// <summary> /// 读取数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="hashCode">哈希码</param> public static T Get<T>(string key, int hashCode) { return (T)mc.Get(key, hashCode); } /// <summary> /// 读取数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="asString">是否把值作为字符串返回</param> public static T Get<T>(string key, object value, bool asString) { return (T)mc.Get(key, value, asString); } #endregion /// <summary> /// 读取数据缓存 /// </summary> /// <param name="key">键</param> public static object Get(string key) { return mc.Get(key); } /// <summary> /// 读取数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="hashCode">哈希码</param> public static object Get(string key, int hashCode) { return mc.Get(key, hashCode); } /// <summary> /// 读取数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="asString">是否把值作为字符串返回</param> public static object Get(string key, object value, bool asString) { return mc.Get(key, value, asString); } #endregion #region 批量写(Set) /// <summary> /// 批量设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public static void SetMultiple(string[] keys, object[] values) { for (int i = 0; i < keys.Length; i++) { mc.Set(keys[i], values[i]); } } /// <summary> /// 批量设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="hashCode">哈希码</param> public static void SetMultiple(string[] keys, object[] values, int[] hashCodes) { for (int i = 0; i < keys.Length; i++) { mc.Set(keys[i], values[i], hashCodes[i]); } } /// <summary> /// 批量设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void SetMultiple(string[] keys, object[] values, DateTime[] expirys) { for (int i = 0; i < keys.Length; i++) { mc.Set(keys[i], values[i], expirys[i]); } } /// <summary> /// 批量设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void Set(string[] keys, object[] values, DateTime[] expirys, int[] hashCodes) { for (int i = 0; i < keys.Length; i++) { mc.Set(keys[i], values[i], expirys[i], hashCodes[i]); } } #endregion #region 批量读取(Multiple),返回哈希表 Hashtable /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> public static Hashtable GetMultiple(string[] keys) { return mc.GetMultiple(keys); } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> public static Hashtable GetMultiple(string[] keys, int[] hashCodes) { return mc.GetMultiple(keys, hashCodes); } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> /// <param name="asString">所有值返回字符</param> public static Hashtable GetMultiple(string[] keys, int[] hashCodes, bool asString) { return mc.GetMultiple(keys, hashCodes, asString); } #endregion #region 批量读取(Multiple),返回对象数组object[] /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> public static object[] GetMultipleArray(string[] keys) { return mc.GetMultipleArray(keys); } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> public static object[] GetMultipleArray(string[] keys, int[] hashCodes) { return mc.GetMultipleArray(keys, hashCodes); } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> /// <param name="asString">所有值返回字符</param> public static object[] GetMultipleArray(string[] keys, int[] hashCodes, bool asString) { return mc.GetMultipleArray(keys, hashCodes, asString); } #endregion #region 批量读取(Multiple),返回泛型集合List[T] /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> public static List<T> GetMultipleList<T>(string[] keys) { object[] obj = mc.GetMultipleArray(keys); List<T> list = new List<T>(); foreach (object o in obj) { list.Add((T)o); } return list; } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> public static List<T> GetMultipleList<T>(string[] keys, int[] hashCodes) { object[] obj = mc.GetMultipleArray(keys, hashCodes); List<T> list = new List<T>(); foreach (object o in obj) { list.Add((T)o); } return list; } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> /// <param name="asString">所有值返回字符</param> public static List<T> GetMultipleList<T>(string[] keys, int[] hashCodes, bool asString) { object[] obj = mc.GetMultipleArray(keys, hashCodes, asString); List<T> list = new List<T>(); foreach (object o in obj) { list.Add((T)o); } return list; } #endregion #region 替换更新(Replace) /// <summary> /// 替换更新数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public static void Replace(string key, object value) { mc.Replace(key, value); } /// <summary> /// 替换更新数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="hashCode">哈希码</param> public static void Replace(string key, object value, int hashCode) { mc.Replace(key, value, hashCode); } /// <summary> /// 替换更新数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void Replace(string key, object value, DateTime expiry) { mc.Replace(key, value, expiry); } /// <summary> /// 替换更新数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void Replace(string key, object value, DateTime expiry, int hashCode) { mc.Replace(key, value, expiry, hashCode); } #endregion #region 删除(Delete) /// <summary> ///删除指定条件缓存 /// </summary> /// <param name="key">键</param> public static bool Delete(string key) { return mc.Delete(key); } /// <summary> /// 删除指定条件缓存 /// </summary> /// <param name="key">键</param> /// <param name="hashCode">哈希码</param> /// <param name="expiry">过期时间</param> public static bool Delete(string key, int hashCode, DateTime expiry) { return mc.Delete(key, hashCode, expiry); } /// <summary> /// 删除指定条件缓存 /// </summary> /// <param name="key">键</param> /// <param name="expiry">过期时间</param> public static bool Delete(string key, DateTime expiry) { return mc.Delete(key, expiry); } /// <summary> /// 移除全部缓存 /// </summary> public static void RemovAllCache() { mc.FlushAll(); } /// <summary> /// 移除全部缓存 /// </summary> /// <param name="list">移除指定服务器缓存</param> public static void RemovAllCache(ArrayList list) { mc.FlushAll(list); } #endregion #region 是否存在(Exists) /// <summary> /// 判断指定键的缓存是否存在 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static bool IsExists(string key) { return mc.KeyExists(key); } #endregion #region 数值增减 #region 存储一个数值元素 /// <summary> /// 存储一个数值元素 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static bool StoreCounter(string key, long counter) { return mc.StoreCounter(key, counter); } /// <summary> /// 存储一个数值元素 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <param name="hashCode">哈希码</param> /// <returns></returns> public static bool StoreCounter(string key, long counter, int hashCode) { return mc.StoreCounter(key, counter, hashCode); } #endregion #region 获取一个数值元素 /// <summary> /// 获取一个数值元素 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static long GetCounter(string key) { return mc.GetCounter(key); } /// <summary> /// 获取一个数值元素 /// </summary> /// <param name="key">键</param> /// <param name="hashCode">哈希码</param> /// <returns></returns> public static long GetCounter(string key, int hashCode) { return mc.GetCounter(key, hashCode); } #endregion #region 增加一个数值元素的值(Increment) /// <summary> /// 将一个数值元素增加。 如果元素的值不是数值类型,将其作为0处理 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static long Increment(string key) { return mc.Increment(key); } /// <summary> /// 将一个数值元素增加。 如果元素的值不是数值类型,将其作为0处理 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <returns></returns> public static long Increment(string key, long inc) { return mc.Increment(key, inc); } /// <summary> /// 将一个数值元素增加。 如果元素的值不是数值类型,将其作为0处理 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <param name="hashCode">哈希码</param> /// <returns></returns> public static long Increment(string key, long inc, int hashCode) { return mc.Increment(key, inc, hashCode); } #endregion #region 减小一个数值元素的值(Decrement) /// <summary> /// 减小一个数值元素的值,减小多少由参数offset决定。 如果元素的值不是数值,以0值对待。如果减小后的值小于0,则新的值被设置为0 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static long Decrement(string key) { return mc.Decrement(key); } /// <summary> /// 减小一个数值元素的值,减小多少由参数offset决定。 如果元素的值不是数值,以0值对待。如果减小后的值小于0,则新的值被设置为0 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <returns></returns> public static long Decrement(string key, long inc) { return mc.Decrement(key, inc); } /// <summary> /// 减小一个数值元素的值,减小多少由参数offset决定。 如果元素的值不是数值,以0值对待。如果减小后的值小于0,则新的值被设置为0 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <param name="hashCode">哈希码</param> /// <returns></returns> public static long Decrement(string key, long inc, int hashCode) { return mc.Decrement(key, inc, hashCode); } #endregion #endregion #endregion #region 指定服务器 #region 获取(Get) /// <summary> /// 从指定服务器获取 /// </summary> /// <param name="server">服务器,Svr1,Svr2</param> /// <param name="key">键</param> /// <returns></returns> public static object GetFrom(string server, string key) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Get(key); } /// <summary> /// 从指定服务器获取 /// </summary> /// <param name="server">服务器,Svr1,Svr2</param> /// <param name="key">键</param> /// <param name="hashCode">哈希码</param> public static object GetFrom(string server, string key, int hashCode) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Get(key, hashCode); } /// <summary> /// 从指定服务器获取 /// </summary> /// <param name="server">服务器,Svr1,Svr2</param> /// <param name="key">键</param> /// <param name="asString">是否把值作为字符串返回</param> public static object GetFrom(string server, string key, object value, bool asString) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Get(key, value, asString); } #endregion #region 写入(Set) /// <summary> /// 设置数据缓存 /// </summary> /// <param name="server">服务器,格式为Svr1,Svr2,Svr3,对应配置文件host</param> /// <param name="key">键</param> /// <param name="value">值</param> public static void SetTo(string server, string key, object value) { MemcachedClient client = GetClient(server); client.PoolName = server; client.Set(key, value); } /// <summary> /// 设置数据缓存 /// </summary> /// <param name="server">服务器,格式为Svr1,Svr2,Svr3,对应配置文件host</param> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="hashCode">哈希码</param> public static void SetTo(string server, string key, object value, int hashCode) { MemcachedClient client = GetClient(server); client.PoolName = server; client.Set(key, value, hashCode); } /// <summary> /// 设置数据缓存 /// </summary> /// <param name="server">服务器,格式为Svr1,Svr2,Svr3,对应配置文件host</param> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void SetTo(string server, string key, object value, DateTime expiry) { MemcachedClient client = GetClient(server); client.PoolName = server; client.Set(key, value, expiry); } /// <summary> /// 设置数据缓存 /// </summary> /// <param name="server">服务器,格式为Svr1,Svr2,Svr3,对应配置文件host</param> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void SetTo(string server, string key, object value, DateTime expiry, int hashCode) { MemcachedClient client = GetClient(server); client.PoolName = server; client.Set(key, value, expiry, hashCode); } #endregion #region 批量写(Set) /// <summary> /// 批量设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public static void SetMultipleTo(string server, string[] keys, object[] values) { MemcachedClient client = GetClient(server); client.PoolName = server; for (int i = 0; i < keys.Length; i++) { client.Set(keys[i], values[i]); } } /// <summary> /// 批量设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="hashCode">哈希码</param> public static void SetMultipleTo(string server, string[] keys, object[] values, int[] hashCodes) { MemcachedClient client = GetClient(server); client.PoolName = server; for (int i = 0; i < keys.Length; i++) { client.Set(keys[i], values[i], hashCodes[i]); } } /// <summary> /// 批量设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void SetMultipleTo(string server, string[] keys, object[] values, DateTime[] expirys) { MemcachedClient client = GetClient(server); client.PoolName = server; for (int i = 0; i < keys.Length; i++) { client.Set(keys[i], values[i], expirys[i]); } } /// <summary> /// 批量设置数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void SetMultipleTo(string server, string[] keys, object[] values, DateTime[] expirys, int[] hashCodes) { MemcachedClient client = GetClient(server); client.PoolName = server; for (int i = 0; i < keys.Length; i++) { client.Set(keys[i], values[i], expirys[i], hashCodes[i]); } } #endregion #region 批量读取(Multiple),返回哈希表 Hashtable /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> public static Hashtable GetMultipleFrom(string server, string[] keys) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.GetMultiple(keys); } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> public static Hashtable GetMultipleFrom(string server, string[] keys, int[] hashCodes) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.GetMultiple(keys, hashCodes); } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> /// <param name="asString">所有值返回字符</param> public static Hashtable GetMultipleFrom(string server, string[] keys, int[] hashCodes, bool asString) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.GetMultiple(keys, hashCodes, asString); } #endregion #region 批量读取(Multiple),返回对象数组object[] /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> public static object[] GetMultipleArrayFrom(string server, string[] keys) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.GetMultipleArray(keys); } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> public static object[] GetMultipleArrayFrom(string server, string[] keys, int[] hashCodes) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.GetMultipleArray(keys, hashCodes); } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> /// <param name="asString">所有值返回字符</param> public static object[] GetMultipleArrayFrom(string server, string[] keys, int[] hashCodes, bool asString) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.GetMultipleArray(keys, hashCodes, asString); } #endregion #region 批量读取(Multiple),返回泛型集合List[T] /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> public static List<T> GetMultipleListFrom<T>(string server, string[] keys) { MemcachedClient client = GetClient(server); client.PoolName = server; object[] obj = client.GetMultipleArray(keys); List<T> list = new List<T>(); foreach (object o in obj) { list.Add((T)o); } return list; } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> public static List<T> GetMultipleListFrom<T>(string server, string[] keys, int[] hashCodes) { MemcachedClient client = GetClient(server); client.PoolName = server; object[] obj = client.GetMultipleArray(keys, hashCodes); List<T> list = new List<T>(); foreach (object o in obj) { list.Add((T)o); } return list; } /// <summary> /// 批量读取数据缓存 /// </summary> /// <param name="keys">键集合</param> /// <param name="hashCodes">哈希码集合</param> /// <param name="asString">所有值返回字符</param> public static List<T> GetMultipleListFrom<T>(string server, string[] keys, int[] hashCodes, bool asString) { MemcachedClient client = GetClient(server); client.PoolName = server; object[] obj = client.GetMultipleArray(keys, hashCodes, asString); List<T> list = new List<T>(); foreach (object o in obj) { list.Add((T)o); } return list; } #endregion #region 替换更新(Replace) /// <summary> /// 替换更新数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public static void ReplaceFrom(string server, string key, object value) { MemcachedClient client = GetClient(server); client.PoolName = server; client.Replace(key, value); } /// <summary> /// 替换更新数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="hashCode">哈希码</param> public static void ReplaceFrom(string server, string key, object value, int hashCode) { MemcachedClient client = GetClient(server); client.PoolName = server; client.Replace(key, value, hashCode); } /// <summary> /// 替换更新数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void ReplaceFrom(string server, string key, object value, DateTime expiry) { MemcachedClient client = GetClient(server); client.PoolName = server; client.Replace(key, value, expiry); } /// <summary> /// 替换更新数据缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> public static void ReplaceFrom(string server, string key, object value, DateTime expiry, int hashCode) { MemcachedClient client = GetClient(server); client.PoolName = server; client.Replace(key, value, expiry, hashCode); } #endregion #region 删除(Delete) /// <summary> ///删除指定条件缓存 /// </summary> /// <param name="key">键</param> public static bool DeleteFrom(string server, string key) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Delete(key); } /// <summary> /// 删除指定条件缓存 /// </summary> /// <param name="key">键</param> /// <param name="hashCode">哈希码</param> /// <param name="expiry">过期时间</param> public static bool DeleteFrom(string server, string key, int hashCode, DateTime expiry) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Delete(key, hashCode, expiry); } /// <summary> /// 删除指定条件缓存 /// </summary> /// <param name="key">键</param> /// <param name="expiry">过期时间</param> public static bool DeleteFrom(string server, string key, DateTime expiry) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Delete(key, expiry); } /// <summary> /// 移除全部缓存 /// </summary> public static void RemovAllCacheFrom(string server) { MemcachedClient client = GetClient(server); client.PoolName = server; client.FlushAll(); } /// <summary> /// 移除全部缓存 /// </summary> /// <param name="list">移除指定服务器缓存</param> public static void RemovAllCacheFrom(string server, ArrayList list) { MemcachedClient client = GetClient(server); client.PoolName = server; client.FlushAll(list); } #endregion #region 是否存在(Exists) /// <summary> /// 判断指定键的缓存是否存在 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static bool IsExists(string server, string key) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.KeyExists(key); } #endregion #region 数值增减 #region 存储一个数值元素 /// <summary> /// 存储一个数值元素 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static bool StoreCounterTo(string server, string key, long counter) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.StoreCounter(key, counter); } /// <summary> /// 存储一个数值元素 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <param name="hashCode">哈希码</param> /// <returns></returns> public static bool StoreCounterTo(string server, string key, long counter, int hashCode) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.StoreCounter(key, counter, hashCode); } #endregion #region 获取一个数值元素 /// <summary> /// 获取一个数值元素 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static long GetCounterFrom(string server, string key) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.GetCounter(key); } /// <summary> /// 获取一个数值元素 /// </summary> /// <param name="key">键</param> /// <param name="hashCode">哈希码</param> /// <returns></returns> public static long GetCounterFrom(string server, string key, int hashCode) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.GetCounter(key, hashCode); } #endregion #region 增加一个数值元素的值(Increment) /// <summary> /// 将一个数值元素增加。 如果元素的值不是数值类型,将其作为0处理 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static long IncrementTo(string server, string key) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Increment(key); } /// <summary> /// 将一个数值元素增加。 如果元素的值不是数值类型,将其作为0处理 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <returns></returns> public static long IncrementTo(string server, string key, long inc) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Increment(key, inc); } /// <summary> /// 将一个数值元素增加。 如果元素的值不是数值类型,将其作为0处理 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <param name="hashCode">哈希码</param> /// <returns></returns> public static long IncrementTo(string server, string key, long inc, int hashCode) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Increment(key, inc, hashCode); } #endregion #region 减小一个数值元素的值(Decrement) /// <summary> /// 减小一个数值元素的值,减小多少由参数offset决定。 如果元素的值不是数值,以0值对待。如果减小后的值小于0,则新的值被设置为0 /// </summary> /// <param name="key">键</param> /// <returns></returns> public static long DecrementFrom(string server, string key) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Decrement(key); } /// <summary> /// 减小一个数值元素的值,减小多少由参数offset决定。 如果元素的值不是数值,以0值对待。如果减小后的值小于0,则新的值被设置为0 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <returns></returns> public static long DecrementFrom(string server, string key, long inc) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Decrement(key, inc); } /// <summary> /// 减小一个数值元素的值,减小多少由参数offset决定。 如果元素的值不是数值,以0值对待。如果减小后的值小于0,则新的值被设置为0 /// </summary> /// <param name="key">键</param> /// <param name="inc">增长幅度</param> /// <param name="hashCode">哈希码</param> /// <returns></returns> public static long DecrementFrom(string server, string key, long inc, int hashCode) { MemcachedClient client = GetClient(server); client.PoolName = server; return client.Decrement(key, inc, hashCode); } #endregion #endregion #endregion } //Singleton /// <summary> /// 泛型单例模式 /// </summary> /// <typeparam name="T"></typeparam> public class Singleton<T> where T : class { private static object locobj = new object(); private static T _current = null; public static T GetInstance() { //双重锁定,保证多线程时安全。 if (_current == null) { lock (locobj) { if (_current == null) { //instance = new T(); //需要非公共的无参构造函数,不能使用new T() ,new不支持非公共的无参构造函数 _current = Activator.CreateInstance(typeof(T), true) as T;//第二个参数防止异常:“没有为该对象定义无参数的构造函数。” } } } return _current; } }
2、测试类库
static void Main(string[] args) { #region //// Memcached服务器列表 //// 如果有多台服务器,则以逗号分隔,例如:"192.168.80.10:11211","192.168.80.11:11211" //string[] serverList = ConfigurationManager.AppSettings["memservers"].Split(','); //// 初始化SocketIO池 //string poolName = "MyPool"; //SockIOPool sockIOPool = SockIOPool.GetInstance(poolName); //// 添加服务器列表 //sockIOPool.SetServers(serverList); //// 设置连接池初始数目 //sockIOPool.InitConnections = 3; //// 设置连接池最小连接数目 //sockIOPool.MinConnections = 3; //// 设置连接池最大连接数目 //sockIOPool.MaxConnections = 5; //// 设置连接的套接字超时时间(单位:毫秒) //sockIOPool.SocketConnectTimeout = 1000; //// 设置套接字超时时间(单位:毫秒) //sockIOPool.SocketTimeout = 3000; //// 设置维护线程运行的睡眠时间:如果设置为0,那么维护线程将不会启动 //sockIOPool.MaintenanceSleep = 30; //// 设置SockIO池的故障标志 //sockIOPool.Failover = true; //// 是否用nagle算法启动 //sockIOPool.Nagle = false; //// 正式初始化容器 //sockIOPool.Initialize(); //// 获取Memcached客户端实例 //MemcachedClient memClient = new MemcachedClient(); //// 指定客户端访问的SockIO池 //memClient.PoolName = poolName; //// 是否启用压缩数据:如果启用了压缩,数据压缩长于门槛的数据将被储存在压缩的形式 //memClient.EnableCompression = false; //Console.WriteLine("----------------------------测试开始----------------------------"); //// 01.简单的添加与读取操作 //memClient.Set("test1", "edisonchou"); //Console.WriteLine("test1:{0}", memClient.Get("test1")); //// 02.先添加后修改再读取操作 //memClient.Set("test2", "jacky"); //Console.WriteLine("test2:{0}", memClient.Get("test2")); //memClient.Set("test2", "edwin"); //Console.WriteLine("test2:{0}", memClient.Get("test2")); //memClient.Replace("test2", "lousie"); //Console.WriteLine("test2:{0}", memClient.Get("test2")); //// 03.判断Key值是否存在 //if (memClient.KeyExists("test2")) //{ // Console.WriteLine("Key:test2 is existed"); //} //// 04.删除指定Key值的数据 //memClient.Add("test3", "memcached"); //Console.WriteLine("test3:{0}", memClient.Get("test3")); //memClient.Delete("test3"); //if (!memClient.KeyExists("test3")) //{ // Console.WriteLine("Key:test3 is not existed"); //} //// 05.设置数据过期时间:5秒后过期 //memClient.Add("test4", "expired", DateTime.Now.AddSeconds(5)); //Console.WriteLine("test4:{0}", memClient.Get("test4")); //Console.WriteLine("Please waiting the sleeping time"); //System.Threading.Thread.Sleep(6000); //if (!memClient.KeyExists("test4")) //{ // Console.WriteLine("test4 is expired"); //} //Console.WriteLine("----------------------------测试完成----------------------------"); //// 关闭SockIO池 //sockIOPool.Shutdown(); #endregion MemcachedClient client = MemcachedHelper.GetClient("memservers"); client.Set("name", "mopheify", DateTime.Now.AddMinutes(2)); var obj= client.Get("name"); Console.WriteLine(obj==null?"Not Hid":obj.ToString()); Console.ReadKey(); }
3、简单封装
public interface ICache { bool ContainKey(string argKey); bool Set(string argKey, object argValue); bool Set(string argKey, object argValue, DateTime argDateExpiration); bool Replace(string argKey, object argValue); bool Replace(string argKey, object argValue, DateTime argDateExpiration); object Get(string argKey); bool Remove(string argKey); bool Remove(string argKey, DateTime argDateExpiration); bool Remove(); bool Remove(ArrayList servers); } public interface ICache { bool ContainKey(string argKey); bool Set(string argKey, object argValue); bool Set(string argKey, object argValue, DateTime argDateExpiration); bool Replace(string argKey, object argValue); bool Replace(string argKey, object argValue, DateTime argDateExpiration); object Get(string argKey); bool Remove(string argKey); bool Remove(string argKey, DateTime argDateExpiration); bool Remove(); bool Remove(ArrayList servers); } 接口实现代码 public class MemCachedHelper2 : ICache { private static object lockobj = new object(); private static MemcachedClient memClient = null; public MemCachedHelper2(string[] serverList, string poolName = "myPool") { // 初始化SocketIO池 SockIOPool sockIOPool = SockIOPool.GetInstance(poolName); // 添加服务器列表 sockIOPool.SetServers(serverList); // 设置连接池初始数目 sockIOPool.InitConnections = 3; // 设置连接池最小连接数目 sockIOPool.MinConnections = 3; // 设置连接池最大连接数目 sockIOPool.MaxConnections = 5; // 设置连接的套接字超时时间(单位:毫秒) sockIOPool.SocketConnectTimeout = 1000; // 设置套接字超时时间(单位:毫秒) sockIOPool.SocketTimeout = 3000; // 设置维护线程运行的睡眠时间:如果设置为0,那么维护线程将不会启动 sockIOPool.MaintenanceSleep = 30; // 设置SockIO池的故障标志 sockIOPool.Failover = true; // 是否用nagle算法启动 sockIOPool.Nagle = false; // 正式初始化容器 sockIOPool.Initialize(); //单例生成客户端 if (memClient == null) { lock (lockobj) { if (memClient == null) { memClient = new MemcachedClient(); memClient.PoolName = poolName; } } } } // public static MemcachedClient GetInstance() { return memClient; } /// <summary> /// 值是否存在 /// </summary> /// <param name="argKey"></param> /// <returns></returns> public bool ContainKey(string argKey) { return memClient.Get(argKey) == null ? false : true; } public bool Set(string argKey, object argValue) { return memClient.Set(argKey, argValue); } public bool Set(string argKey, object argValue, DateTime argDateExpiration) { return memClient.Set(argKey, argValue, argDateExpiration); } public bool Replace(string argKey, object argValue) { return memClient.Replace(argKey, argValue); } public bool Replace(string argKey, object argValue, DateTime argDateExpiration) { return memClient.Replace(argKey, argValue, argDateExpiration); } public object Get(string argKey) { return memClient.Get(argKey); } public bool Remove(string argKey) { return memClient.Delete(argKey); } public bool Remove(string argKey, DateTime argDateExpiration) { return memClient.Delete(argKey, argDateExpiration); } public bool Remove() { return memClient.FlushAll(); } public bool Remove(System.Collections.ArrayList servers) { return memClient.FlushAll(servers); } }
参考资料