Session 共享(Custom模式)By Memcached(原创)
1、web.config配置:
<machineKey decryptionKey="FD69B2EB9A11E3063518F1932E314E4AA1577BF0B824F369" validationKey="5F32295C31223A362286DD5777916FCD0FD2A8EF882783FD3E29AB1FCDFE931F8FA45A8E468B7A40269E50A748778CBB8DB2262D44A86BBCEA96DCA46CBC05C3" validation="SHA1" decryption="Auto"/>
<sessionState mode="Custom" customProvider="SessionProvider" timeout="120">
<providers>
<add name="SessionProvider" type="Entity.MemcachedSessionProvider, Entity" />
</providers>
</sessionState> <httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="CrossDomainCookieModule" type="Entity.SessionProviderHttpModule, Entity"/>
</httpModules>
2、Entity.MemcachedSessionProvider 代码
public class MemcachedSessionProvider : SessionStateStoreProviderBase
{
private IMemcacheBiz _Client;
private static readonly int _DefaultSessionExpireMinute = 20;
private int _timeout; public MemcachedSessionProvider()
{
_Client = new MemcacheBiz();
} public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
string applicationVirtualPath = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
Configuration webconfig = WebConfigurationManager.OpenWebConfiguration(applicationVirtualPath);
SessionStateSection _objConfig = (SessionStateSection)webconfig.GetSection("system.web/sessionState"); if (_objConfig == null || _objConfig.Timeout == null || _objConfig.Timeout.Minutes <= 0)
{
this._timeout = _DefaultSessionExpireMinute;
}
else
{
this._timeout = _objConfig.Timeout.Minutes;
}
} public override void InitializeRequest(HttpContext context)
{
//throw new NotImplementedException();
} public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
{
return new SessionStateStoreData(new SessionStateItemCollection(),
SessionStateUtility.GetSessionStaticObjects(context), timeout);
} public override void CreateUninitializedItem(HttpContext context, string id, int timeout)
{
MemcachedSessionObject sessionObject
= new MemcachedSessionObject
{
Content = null,
Locked = false,
SetTime = DateTime.Now,
LockId = 0,
ActionFlag = 1
};
_Client.Set(id, sessionObject, TimeSpan.FromMinutes(timeout));
} public override void Dispose()
{
//throw new NotImplementedException();
} public override void EndRequest(HttpContext context)
{
//throw new NotImplementedException();
} public override SessionStateStoreData GetItem(HttpContext context, string id, out bool locked,
out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
{
SessionStateStoreData sessionStateStoreData = null;
MemcachedSessionObject memcachedSessionObject = null;
DateTime setTime = DateTime.Now; lockAge = TimeSpan.Zero;
lockId = null;
locked = false;
actions = SessionStateActions.None;
memcachedSessionObject = _Client.Get(id) as MemcachedSessionObject; if (memcachedSessionObject != null)
{
//如果已经锁定
if (memcachedSessionObject.Locked)
{
lockAge = memcachedSessionObject.LockAge;
lockId = memcachedSessionObject.LockId;
locked = memcachedSessionObject.Locked;
actions = (SessionStateActions)memcachedSessionObject.ActionFlag;
return sessionStateStoreData;
} memcachedSessionObject.LockId++;
memcachedSessionObject.SetTime = setTime; _Client.Set(id, memcachedSessionObject); actions = (SessionStateActions)memcachedSessionObject.ActionFlag;
lockId = memcachedSessionObject.LockId;
lockAge = memcachedSessionObject.LockAge; if (actions == SessionStateActions.InitializeItem)
sessionStateStoreData = this.CreateNewStoreData(context, _timeout);
else
sessionStateStoreData = this.Deserialize(context, memcachedSessionObject.Content, _timeout); return sessionStateStoreData;
} return sessionStateStoreData;
} public override SessionStateStoreData GetItemExclusive(HttpContext context, string id, out bool locked,
out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
{
return GetItem(context, id, out locked, out lockAge, out lockId, out actions);
} public override void ReleaseItemExclusive(HttpContext context, string id, object lockId)
{
MemcachedSessionObject memcachedSessionObject = _Client.Get(id) as MemcachedSessionObject;
if (memcachedSessionObject != null)
{
memcachedSessionObject.Locked = false;
memcachedSessionObject.LockId = (Int32)lockId;
_Client.Set(id, memcachedSessionObject, TimeSpan.FromMinutes(_timeout));
}
} public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
{
_Client.Delete(id);
} public override void ResetItemTimeout(HttpContext context, string id)
{
object obj = _Client.Get(id);
if (obj != null)
{
_Client.Set(id, obj, TimeSpan.FromMinutes(_timeout));
}
} public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
{
DateTime setTime = DateTime.Now;
byte[] bytes = this.Serialize((SessionStateItemCollection)item.Items);
MemcachedSessionObject memcachedSessionObject = new MemcachedSessionObject
{
LockId = 0,
Locked = false,
Content = bytes,
ActionFlag = 0,
SetTime = setTime
};
_Client.Set(id, memcachedSessionObject, TimeSpan.FromMinutes(item.Timeout));
} public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
{
return false;
} private SessionStateStoreData Deserialize(HttpContext context, byte[] bytes, int timeout)
{
MemoryStream stream = new MemoryStream(bytes);
SessionStateItemCollection collection = new SessionStateItemCollection(); if (stream.Length > 0)
{
BinaryReader reader = new BinaryReader(stream);
collection = SessionStateItemCollection.Deserialize(reader);
} return new SessionStateStoreData(collection, SessionStateUtility.GetSessionStaticObjects(context), timeout);
} private byte[] Serialize(SessionStateItemCollection items)
{
MemoryStream ms = new MemoryStream();
BinaryWriter writer = new BinaryWriter(ms); if (items != null)
items.Serialize(writer); writer.Close(); return ms.ToArray();
}
}
这里面涉到一些memcache的方法,在下一节有说明
Session 共享(Custom模式)By Memcached(原创)的更多相关文章
- Session 共享(StateServer模式)(原创)
Session 共享要注意两点: 1.必须在同一个域名下 2.StateServer模式是把session保存在同一台服务器上的进程:aspnet_state.exe里面,当然也可以保存在memcac ...
- Tomcat通过Memcached实现session共享的完整部署记录
对于web应用集群的技术实现而言,最大的难点就是:如何能在集群中的多个节点之间保持数据的一致性,会话(Session)信息是这些数据中最重要的一块.要实现这一点, 大体上有两种方式:一种是把所有Ses ...
- Tomcat集群环境下session共享方案 通过memcached 方法实现
对于web应用集群的技术实现而言,最大的难点就是:如何能在集群中的多个节点之间保持数据的一致性,会话(Session)信息是这些数据中最重要的一块.要实现这一点, 大体上有两种方式:一种是把所有Ses ...
- Memcached做Tomcat的session共享
基于cache DB缓存的session共享 基于memcache/redis缓存的session共享.即使用cacheDB存取session信息,应用服务器接受新请求将session信息保存在cac ...
- 项目分布式部署那些事(2):基于OCS(Memcached)的Session共享方案
在不久之前发布了一篇"项目分布式部署那些事(1):ONS消息队列.基于Redis的Session共享,开源共享",因为一些问题我们使用了阿里云的OCS,下面就来简单的介绍和分享下相 ...
- 【转】Nginx+Tomcat+Memcached集群Session共享
cookie是怎样工作的? 例 如,我们创建了一个名字为login的Cookie来包含访问者的信息,创建Cookie时,服务器端的Header如下面所示,这里假设访问者的注册名 是“Michael J ...
- Nginx+Tomcat+memcached负载均衡实现session共享
http://blog.csdn.net/love_ubuntu/article/details/8464983 1. 安装各个软件不用说了. 2. 到tomcat的安装目录lib中,加入: me ...
- 分布式Session共享(二):tomcat+memcached实现session共享
一.前言 本文主要测试memcached实现session共享的实现方式,不讨论如何让nginx参与实现负载均衡等. 二.环境配置 本测试在Window下进行 name version port To ...
- Nginx+Tomcat+Memcached实现tomcat集群和session共享
一.Nginx安装 详见前文:http://www.cnblogs.com/yixiwenwen/p/3574097.html 二.memcached安装和启动 详见前文:http://www.cnb ...
- Nginx + Memcached 实现Session共享的负载均衡
session共享 我们在做站点的试试,通常需要保存用户的一些基本信息,比如登录就会用到Session:当使用Nginx做负载均衡的时候,用户浏览站点的时候会被分配到不同的服务器上,此时如果登录后Se ...
随机推荐
- zookeeper【5】分布式锁
我们常说的锁是单进程多线程锁,在多线程并发编程中,用于线程之间的数据同步,保护共享资源的访问.而分布式锁,指在分布式环境下,保护跨进程.跨主机.跨网络的共享资源,实现互斥访问,保证一致性. 架构图: ...
- libuuid.so: cannot open shared object file: No such file or directory
在玩ngx-lua时候有个 resty-uuid 需要引用 libuuid.so 动态库 打印log提示信息是这样的: libuuid.so: cannot open shared object fi ...
- oracle复杂查询是sql
一.over()分析函数 分组查前几条:select * from test t where (select count(*) from test a where t.type=a.type and ...
- Codeforces Round #353 (Div. 2) B. Restoring Painting 水题
B. Restoring Painting 题目连接: http://www.codeforces.com/contest/675/problem/B Description Vasya works ...
- LogStash日志分析系统
简介 通常日志管理是逐渐崩溃的——当日志对于人们最重要的时候,也就是出现问题的时候,这个渐进的过程就开始了.日志管理一般会经历一下3个阶段: 初级管理员将通过一些传统工具(如cat.tail.sed. ...
- Redis中文API地址
地址:http://redis.readthedocs.org/en/2.4/string.html
- 仿querySeletor 兼容IE 67
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- git diff 打补丁
[root@workstation2017 demo]# git diff old new >cc.diff[root@workstation2017 demo]# cat cc.diffdif ...
- mysql解决datetime与timestamp精确到毫秒的问题
CREATE TABLE `tab1` ( `tab1_id` VARCHAR(11) DEFAULT NULL, `create` TIMESTAMP(3) NULL DEFAULT NULL, ` ...
- UIView 精要概览(持续更新)
--1-- 知识点:为UIView 设置圆角 前提:layer 属性需要 <QuartzCore/QuartzCore.h> 静态库的支持,所以需要提前导入到项目中,并在你的文件中包含#i ...