C#实现Memcached分布式缓存,指定服务器保存变量
说明:Memcached 分为服务器端和客户端, 客户端有多种实现方式,我这里是选择了这个版本 http://sourceforge.net/projects/memcacheddotnet/?source=dlp
第 1 步: 配置环境
1.下载服务器memcached for win32安装。http://www.splinedancer.com/memcached-win32/,www.splinedancer.com/memcached-win32/memcached-1.2.4-Win32-Preview-20080309_bin.zip
我在源码文件 服务器设置 里面附带了memcached.exe,把memcached.exe这个文件拷贝到C盘新建 文件夹 C:\memcached-1.2.6
2.用管理员方式开口cmd命令窗口 输入: cd C:\memcached-1.2.6 然后输入memcached.exe -d install 就可以把memcached安装为windows服务了。
3.启动服务后,memcached服务默认占用的端口是11211,占用的最大内存默认是64M。
4.可以自己修改端口号,但是需要修改注册表
打开注册表,找到:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached Server
其中的ImagePath项的值为:"c:\memcached-1.2.6\memcached.exe" -d runservice
改成:"c:\memcached-1.2.6\memcached.exe" -p 12345 -m 1024 -d runservice
表示可以 缓存 1G数据。端口 12345
第 2 步: 打开Visual Studio 2010 ,新建项目www.memcached.com,这步我就省略了。
第 3步: 添加缓存帮组文件
using System; using System.Web; using System.Linq; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Configuration; using Memcached.ClientLibrary; namespace www.memcached.com { /// <summary> /// 页 面 名:缓存管理类<br/> /// 说 明:设置、获取、移除Cache<br/> /// 作 者:xxx<br/> /// 时 间:2012-12-12(神奇的数字,传说中的12K)<br/> /// 修 改 者:<br/> /// 修改时间:<br/> /// </summary> public class CacheHelper { #region 变量和构造函数 //缓存服务器地址和端口,这样就实现了分布式缓存。服务器可以多个,用Socket读写数据"127.0.0.1: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 CacheHelper() { 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; pool.SocketTimeout = 100; 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("Svr1", ConfigurationManager.AppSettings["Svr1"]); Servers.Add("Svr2", ConfigurationManager.AppSettings["Svr2"]); } private CacheHelper() { } #endregion #region 获取客户端 public static MemcachedClient GetClient(string server) { MemcachedClient current = Singleton<MemcachedClient>.Instance; 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 } }
第 4步: 测试默认服务器
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Memcached.ClientLibrary; namespace www.memcached.com { [Serializable] class A { public string Name { get; set; } } public partial class Test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { CacheHelper.RemovAllCache(); /*例子1 保存复杂对象*/ A[] a = new A[] { new A { Name = "刘德华" }, new A { Name = "施瓦辛格" }, new A { Name = "太上老君" } }; CacheHelper.Set("name", a, DateTime.Now.AddSeconds(10)); object c = CacheHelper.Get("name"); A[] b = (A[])c; Response.Write(b[2].Name + "<br/>"); /*例子2 批量获取对象*/ int[] array = { 1, 2, 3, 4, 5, 6, 7 }; foreach (int i in array) { CacheHelper.Set("array" + i, i); } string[] keys = { "array1", "array2", "array3", "array4", "array5", "array6", "array7" }; object[] obj = CacheHelper.GetMultipleArray(keys); foreach (object o in obj) { Response.Write(o + "<br/>"); } /*例子3 获取泛型*/ A a3 = new A { Name = "我是对象" }; CacheHelper.Set("TType", a3); A a4 = CacheHelper.Get<A>("TType"); Response.Write(a4.Name + "<br/>"); /*例子4 删除*/ try { Response.Write("删除对象TType " + CacheHelper.Delete("TType") + "<br/>"); A a5 = CacheHelper.Get<A>("TType"); Response.Write(a5.Name + "<br/>"); } catch (Exception exe) { Response.Write("获取对象报错,说明对象已经删除,错误信息是: " + exe.Message + "<br/>"); Response.Write("删除对象后,判断是否存在: CacheHelper.IsExists: " + CacheHelper.IsExists("TType") + "<br/>"); } /*例子5 增加,减少*/ long counter = 10; CacheHelper.StoreCounter("number", counter); Response.Write("number增加前是: " + CacheHelper.GetCounter("number") + "<br/>"); CacheHelper.Increment("number"); Response.Write("对number增加后是: " + CacheHelper.GetCounter("number") + "<br/>"); CacheHelper.Increment("number", 100); Response.Write("对number增加100后是: " + CacheHelper.GetCounter("number") + "<br/>"); CacheHelper.Decrement("number", 100); Response.Write("对number减去100后是: " + CacheHelper.GetCounter("number") + "<br/>"); /*例子6 批量读取 泛型 测试*/ A[] a6 = new A[] { new A { Name = "李嘉图" }, new A { Name = "亚当斯密" }, new A { Name = "苏格拉底" } }; string[] k6 = { "economy1", "economy2", "economy3" }; CacheHelper.SetMultiple(k6, a6); Response.Write("下面是 泛型 批量 获取对象<br/>"); List<A> list = CacheHelper.GetMultipleList<A>(k6); foreach (A p in list) { Response.Write(p.Name + "<br/>"); } } } }
第 5步: 测试指定服务器
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace www.memcached.com { public partial class Test4 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { CacheHelper.SetTo("Svr1", "Abc", "good1"); CacheHelper.SetTo("Svr2", "Abc", "good2"); Response.Write("第一台服务器:"+CacheHelper.GetFrom("Svr1", "Abc")+"<br/>"); Response.Write("第二台服务器:" + CacheHelper.GetFrom("Svr2", "Abc") + "<br/>"); CacheHelper.StoreCounterTo("Svr1","Count",1); CacheHelper.IncrementTo("Svr1", "Count", 10); Response.Write("自增结果:" + CacheHelper.GetCounterFrom("Svr1", "Count") + "<br/>"); } } }
第 6步: 项目配置文件
<?xml version="1.0"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <appSettings> <add key="Svr1" value="127.0.0.1:12345"/> <add key="Svr2" value="192.168.1.26:11211"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> <authentication mode="Forms"> <forms loginUrl="~/Account/Login.aspx" timeout="2880" /> </authentication> <membership> <providers> <clear/> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> </providers> </membership> <profile> <providers> <clear/> <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/> </providers> </profile> <roleManager enabled="false"> <providers> <clear/> <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" /> <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> </providers> </roleManager> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
下面给出项目源码 下载地址 https://files.cnblogs.com/HCCZX/www.memcached.com.rar