您的位置:首页 > 数据库 > Memcache

Memcache学习第二课:在C#项目中应用Memcache

2012-11-29 15:39 274 查看
  下载文件: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: