.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 = ; //最大连接数
- pool.MinConnections = ; //最小连接数
- pool.SocketConnectTimeout = ; //Socket连接超时设置
- pool.SocketTimeout = ; //
- 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 = ;
- defaultPool.MinConnections = ;
- defaultPool.SocketConnectTimeout = ;
- defaultPool.SocketTimeout = ;
- 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 = ; 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 = ; 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 = ; 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 = ; 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 = ; 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 = ; 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 = ; 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 = ; 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());
- 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 = ;
- // 设置连接池最小连接数目
- sockIOPool.MinConnections = ;
- // 设置连接池最大连接数目
- sockIOPool.MaxConnections = ;
- // 设置连接的套接字超时时间(单位:毫秒)
- sockIOPool.SocketConnectTimeout = ;
- // 设置套接字超时时间(单位:毫秒)
- sockIOPool.SocketTimeout = ;
- // 设置维护线程运行的睡眠时间:如果设置为0,那么维护线程将不会启动
- sockIOPool.MaintenanceSleep = ;
- // 设置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);
- }
- }
参考资料
.net 使用Memcached的更多相关文章
- 支持 .NET Core 的 Memcached 客户端 EnyimMemcachedCore
1. 介绍 EnyimMemcachedCore 是一个支持 .NET Core 的 Memcached 客户端,是从 EnyimMemcached 迁移至 .NET Core的,源代码托管在 Git ...
- Key/Value之王Memcached初探:二、Memcached在.Net中的基本操作
一.Memcached ClientLib For .Net 首先,不得不说,许多语言都实现了连接Memcached的客户端,其中以Perl.PHP为主. 仅仅memcached网站上列出的语言就有: ...
- ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存
ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存 part 1:给我点时间,允许我感慨一下2016年 正好有时间,总结一下最近使用的一些技术,也算是为2016年画上一个完 ...
- 缓存、队列(Memcached、redis、RabbitMQ)
本章内容: Memcached 简介.安装.使用 Python 操作 Memcached 天生支持集群 redis 简介.安装.使用.实例 Python 操作 Redis String.Hash.Li ...
- 企业做数据缓存是使用Memcached还是选Redis?
企业是使用Memcached还是选Redis? 在构建一款现代且由数据库驱动的Web应用程序并希望使其拥有更为出色的性能表现时,这个问题总会时不时出现.并给每一位开发人员带来困扰.在考虑对应用程序的性 ...
- NoSql1 在Linux(CentOS)上安装memcached及使用
前言: 今天是初五,生活基本要从过年的节奏中回归到正常的生活了,所以想想也该想想与工作有关的事情了.我之前在工作中会经常使用memcached和redis,但是自己一直没有时间系统的好好看 ...
- Memcached简介
在Web服务开发中,服务端缓存是服务实现中所常常采用的一种提高服务性能的方法.其通过记录某部分计算结果来尝试避免再次执行得到该结果所需要的复杂计算,从而提高了服务的运行效率. 除了能够提高服务的运行效 ...
- Linux 服务器 安装 memcached
linux centos 一.memcached的安装 1.下载 memcached-1.4.33.tar.gz.libevent-2.0.22-stable.tar.gz 安装 memcached ...
- Memcached和Redis比较
一.存储 Memcached基本只支持简单的key-value存储方式.Redis除key-value之外,还支持list,set,sorted set,hash等数据结构:Redis支持数据的备份, ...
- 搭建LNAMP环境(七)- PHP7源码安装Memcached和Memcache拓展
上一篇:搭建LNAMP环境(六)- PHP7源码安装MongoDB和MongoDB拓展 一.安装Memcached 1.yum安装libevent事件触发管理器 yum -y install libe ...
随机推荐
- Python中使用Beautiful Soup库的超详细教程
[参考文献] http://www.jb51.net/article/65287.htm
- zabbix监控java内存的脚本
#!/bin/bash # 截取java的pid号 java_pid=`netstat -lnpt |grep |awk -F '/' '{print $1'}` # 截取$jstat命令的位置 js ...
- 商品录入功能v1.0【持续优化中...】
# 录入商品 def goods_record(): print("欢迎使用铜锣辉的购物商城[商品管理][录入商品]".center(30, "*")) whi ...
- doors dxl 遍历object 查找
Module m = current; //m = edit(“xxx”) Object o for o in m do { string sht = o.”shtName” Buffer bf=cr ...
- phpSpreadSheet 中 使用的 一些坑
如果是upupw,它 做了 安全限制...将 上传目录 写成 uploadfiles 等 才能 写进去.. 文件路径 也不要有 中文..很有可以能 下载时 找不到路径....这个太坑...
- Canvas 动态小球重叠效果
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- nginx FastCGI模块配置
这个模块允许nginx同FastCGI协同工作,并且控制哪些参数将被安全传递. location / { fastcgi_pass localhost:9000;# 或者http://ip:9000; ...
- php5 编译安装
#!/bin/bash######################################## File Name: php.sh# Version: V1.0# Author: sun yu ...
- Nginx配置SSL报错 nginx: [emerg] unknown directive "ssl"
Nginx配置SSL报错 nginx: [emerg] unknown directive "ssl" 出现如图所示错误,处理办法如下 去nginx解压目录下执行 ./co ...
- 关于WampServer一些配置修改
1.解决WAMP mysql中文乱码问题(在mysql的my.ini文件中) 1).找到client字段并添加:default-character-set=utf8 2).找到mysql字段并添加: ...