下载文件:BeITMemcached_source,解压后里面是一个解决方案,在BeITMemcached工程中有一个ClientLibrary文件夹和一个Example.cs文件,其中ClientLibrary是用C#实现的memcache源代码,Example.cs是memcache客户端调用示例代码。
去掉Example.cs,将项目属性的Output Type 设置为Class Library后重新编译,将bin目录下生成的dll文件拷贝到自己实际项目中并添加引用。
我的想法是使用memcache存放登陆用户的信息,并分离出来作一台单独的缓存服务器,取代使用session的存放的方式,解决多web服务器间session共享的问题。
在登陆页面:
if (!MemcachedClient.Exists("MyMemcache")) { MemcachedClient.Setup("MyMemcache", new string[] { "127.0.0.1:11211" }); } MemcachedClient memcache = MemcachedClient.GetInstance("MyMemcache"); string sessionID = Guid.NewGuid().ToString(); HttpContext.Current.Response.SetCookie(new HttpCookie("SESSIONID", sessionID)); memcache.Set(sessionID, SysUserEntity);
在验证页面:
if (!MemcachedClient.Exists("MyMemcache")) { MemcachedClient.Setup("MyMemcache", new string[] { "localhost" }); } MemcachedClient memcache = MemcachedClient.GetInstance("MyMemcache"); HttpCookieCollection cookieCollection = HttpContext.Current.Request.Cookies; HttpCookie cookie = cookieCollection.Get("SESSIONID"); if (cookie == null)
{
return false;
}
SysUserEntity user = memcache.Get(cookie.Value) as SysUserEntity; if (user == null) { return false; }