十二12 发表于 2015-8-31 07:42:57

分布式缓存MemCache

  .NET版本服务端    http://pan.baidu.com/share/link?shareid=3505343637&uk=3928651495
  .NET版本客户端    http://pan.baidu.com/share/link?shareid=3511558869&uk=3928651495
  封装类



/// <summary>
/// MemCache帮助类
/// 根据配置文件里的Serverlist节点读取分布式缓存服务器列表 格式为 "127.0.0.1:11211" ,"127.0.0.2:11211"
/// 如果Web.config未配置。则服务器默认为 127.0.0.1:11211
/// </summary>
public class CachedHelper
{
/// <summary>
/// 设置缓存_如果KEY存在_则更新
/// </summary>
/// <param name="Key">Key</param>
/// <param name="Value">Value</param>
/// <param name="times">过期时间点_为当前时间加上此值(单位为妙)</param>
public static void SetMemCache(string Key, object Value, double times)
{
SockIOPool pool;
MemcachedClient mc;
init(out pool, out mc);
mc.Set(Key, Value, DateTime.Now.AddSeconds(times));
pool.Shutdown();//关闭连接池
      }
/// <summary>
/// 设置缓存_如果KEY存在_则更新
/// </summary>
/// <param name="Key">Key</param>
/// <param name="Value">Value</param>
public static void SetMemCache(string Key, object Value)
{
SockIOPool pool;
MemcachedClient mc;
init(out pool, out mc);
mc.Set(Key, Value);
pool.Shutdown();//关闭连接池
      }
/// <summary>
/// 根据Key读取缓存_如果读不到_返回空字符串
/// </summary>
/// <param name="Key"></param>
/// <returns></returns>
public static object GetMemcache(string Key)
{
SockIOPool pool;
MemcachedClient mc;
init(out pool, out mc);
object value = mc.Get(Key) ?? "";
pool.Shutdown();//关闭连接池
return value;
}
/// <summary>
/// 服务器初始化
/// </summary>
/// <param name="pool"></param>
/// <param name="mc"></param>
private static void init(out SockIOPool pool, out MemcachedClient mc)
{
string ConServerlist = System.Configuration.ConfigurationManager.AppSettings.Get("Serverlist");
if (string.IsNullOrEmpty(ConServerlist))
{
ConServerlist = "127.0.0.1:11211";
}
///初始化memcached 服务器端集群列表。
string[] serverlist = ConServerlist.Split(',');
pool = SockIOPool.GetInstance("MemCache");
//设置怎么mem池连接点服务器端。
            pool.SetServers(serverlist);
pool.Initialize();
//创建了一个mem客户端的代理类。
mc = new MemcachedClient();
mc.PoolName = "MemCache";
mc.EnableCompression = false;
}

}
  
页: [1]
查看完整版本: 分布式缓存MemCache