Memcache是一个高性能的分布式的内存对象缓存系统,通过在内存里维护一个统一的巨大的hash表,它能够用来存储各种格式的数据,包括
图像、
视频、
文件以及
数据库检索的结果等。Memcache是danga的一个项目,最早是LiveJournal 服务的,最初为了加速 LiveJournal 访问速度而开发的,后来被很多大型的网站采用。 MemcachedClient mc = MemCachedManager.CacheClient;
//方一
public UserInfo GetCacheData1(string key)
{
UserInfo value = mc.Get(key) as UserInfo;
if (value == null)
{
// 3 分钟到期.在delete操作执行之前,当前key_mutex add只能被添加一次并返回true
if (mc.Add(key + "_mutex", key + "_mutex", DateTime.Now.AddMinutes(3)) == true)
{
value = new UserInfo() { UserName = "daizhj", Email = "daizhj617595@126.com" };// db.get(key);//从加载数据
mc.Set(key, value);
mc.Delete(key + "_mutex");
}
else
{
System.Threading.Thread.Sleep(500);//如果设置过短,可能上面set语法还未生效
value = mc.Get(key) as UserInfo;//sleep之后重试读取cache数据
}
}
return value;
}
memcached服务器端的安装
下载文件:http://www.danga.com/memcached/
1. 解压缩文件到
c:\memcached
2. 命令行输入
'c:\memcached\memcached.exe -d install'
3. 命令行输入
'c:\memcached\memcached.exe -d start'
该命令启动 memcached ,默认监听端口为 11211,通过 memcached.exe -h 可以查看其帮助。
.NET memcached client library
下载文件:https://sourceforge.net/projects/memcacheddotnet/
里面有.net1.1 和 .net2.0的两种版本 还有一个不错的例子。
应用
1. 将Commons.dll,ICSharpCode.SharpZipLib.dll,log4net.dll,Memcached.ClientLibrary.dll 等放到bin目录
2. 引用Memcached.ClientLibrary.dll
3. 代码
//string poolName = "MemcacheIOPool";
if (!IsPostBack)
{
//在应用程序启动时运行的代码
char[] separator = { ',' };
string[] serverlist = ConfigurationManager.AppSettings["Memcached.ServerList"].Split(separator);
SockIOPool pool = SockIOPool.GetInstance();
pool.SetServers(serverlist);
pool.InitConnections = 3;
pool.MinConnections = 3;
pool.MaxConnections = 50;
pool.SocketConnectTimeout = 1000;
pool.SocketTimeout = 3000;
pool.MaintenanceSleep = 30;
pool.Failover = true;
pool.Nagle = false;
pool.Initialize();
}
else
{
MemcachedClient mc = new MemcachedClient();
//mc.PoolName = poolName;
mc.EnableCompression = false;
string key = "user_info";//key值
object obj = new object();
if (mc.KeyExists(key)) //测试缓存中是否存在key的值
{
obj = mc.Get(key);
string user2 = (string)obj;
}
else
{
mc.Set(key, "Text", System.DateTime.Now.AddMinutes(1)); //存储数据到缓存服务器,这里将user这个对象缓存,key 是"user_info1"
}
Response.Write(mc.Get(key));
}
}