可灵活扩展的自定义Session状态存储驱动

时间:2021-10-04 10:21:37

Session是互联网应用中非常重要的玩意儿,对于超过单台部署的站点集群,都会存在会话共享的需求。在web.config中,微软提供了sessionstate节点来定义不同的Session状态存储方式。本文就自定义模式下的Session状态存储驱动提供一些干货。

首先,想要接管Session状态存储,需要了解一些基本的东西。

SessionIDManager

/// <summary>
/// 自定义SessionID管理器
/// </summary>
public class CustomSessionIDManager : SessionIDManager
{
/// <summary>
/// 创建SessionID
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override string CreateSessionID(HttpContext context)
{
return string.Format("{0}.{1}", SessionProviderConfigurationSectionHandler.SessionProviderSettings.SessionProfix, base.CreateSessionID(context));
} /// <summary>
/// 验证
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public override bool Validate(string id)
{
string prefix = string.Empty;
string realId = string.Empty; if (string.IsNullOrEmpty(id) || id.Trim().Length == )
{
return false;
}
var parsedValues = id.Split('.');
if (parsedValues == null || parsedValues.Length != )
{
return false;
} prefix = parsedValues[];
realId = parsedValues[]; return base.Validate(realId);
} }

想要共享Session,肯定就会有SessionID的前缀需求,而SessionIDManager就提供了可自定义的虚方法,这边以CustomSessionIDManager举例。CreateSessionID方法提供了创建SessionID的实现,重载该方法,用{0}.{1}的方式提供基于前缀的SessionID生成。而Validate是拆解带前缀的SessionID来验证真实的SessionID。

SessionStateStoreProviderBase

/// <summary>
/// 自定义Session状态存储驱动
/// </summary>
public sealed class CustomSessionStateStoreProvider : SessionStateStoreProviderBase
{ /// <summary>
/// 构造函数
/// </summary>
public CustomSessionStateStoreProvider()
{
sessionStateStoreBehavior = SessionProviderBehaviorFactory.CreateSessionStateStoreBehaviorInstance();
} /// <summary>
/// Session状态存储行为
/// </summary>
readonly ISessionStateStoreBehavior sessionStateStoreBehavior; /// <summary>
/// 创建新的存储数据
/// </summary>
/// <param name="context"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public override SessionStateStoreData CreateNewStoreData(System.Web.HttpContext context, int timeout)
{
return new SessionStateStoreData(new SessionStateItemCollection(), SessionStateUtility.GetSessionStaticObjects(context), timeout);
} /// <summary>
/// 创建未初始化的项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="timeout"></param>
public override void CreateUninitializedItem(System.Web.HttpContext context, string id, int timeout)
{
sessionStateStoreBehavior.CreateUninitializedItem(context, id, timeout);
} /// <summary>
/// 获取项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="locked"></param>
/// <param name="lockAge"></param>
/// <param name="lockId"></param>
/// <param name="actions"></param>
/// <returns></returns>
public override SessionStateStoreData GetItem(System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
{
return sessionStateStoreBehavior.GetItem(false, context, id, out locked, out lockAge, out lockId, out actions);
} /// <summary>
/// 独占获取项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="locked"></param>
/// <param name="lockAge"></param>
/// <param name="lockId"></param>
/// <param name="actions"></param>
/// <returns></returns>
public override SessionStateStoreData GetItemExclusive(System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
{
return sessionStateStoreBehavior.GetItem(true, context, id, out locked, out lockAge, out lockId, out actions);
} /// <summary>
/// 独占释放项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="lockId"></param>
public override void ReleaseItemExclusive(System.Web.HttpContext context, string id, object lockId)
{
sessionStateStoreBehavior.ReleaseItem(context, id, lockId);
} /// <summary>
/// 移除项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="lockId"></param>
/// <param name="item"></param>
public override void RemoveItem(System.Web.HttpContext context, string id, object lockId, SessionStateStoreData item)
{
sessionStateStoreBehavior.RemoveItem(context, id, lockId);
} /// <summary>
/// 重设项的超时时间
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
public override void ResetItemTimeout(System.Web.HttpContext context, string id)
{
sessionStateStoreBehavior.ResetItemTimeout(context, id);
} /// <summary>
/// 独占设置并释放项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="lockId"></param>
/// <param name="newItem"></param>
public override void SetAndReleaseItemExclusive(System.Web.HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
{
sessionStateStoreBehavior.SetAndReleaseItem(context, id, item, lockId, newItem);
} /// <summary>
/// 回收
/// </summary>
public override void Dispose() { } /// <summary>
/// 结束请求
/// </summary>
/// <param name="context"></param>
public override void EndRequest(System.Web.HttpContext context) { } /// <summary>
/// 初始化请求
/// </summary>
/// <param name="context"></param>
public override void InitializeRequest(System.Web.HttpContext context) { } /// <summary>
/// 设置项过期回掉
/// </summary>
/// <param name="expireCallback"></param>
/// <returns></returns>
public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback) { return false; }
}

SessionStateStoreProviderBase是提供Session状态存储驱动的基类。从基类分析,想要灵活扩展,核心就是对Session存储的那些方法实现进行抽象,让驱动在执行方法的时候不关心实现由谁来提供。因此,写一个SessionStateStoreBehavior接口,在CustomSessionStateStoreProvider的构造函数中,通过工厂在运行时得到实例。

SessionStateStoreBehavior

/// <summary>
/// Session状态存储行为接口
/// </summary>
public interface ISessionStateStoreBehavior
{
/// <summary>
/// 创建未初始化的项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="timeout"></param>
void CreateUninitializedItem(System.Web.HttpContext context, string id, int timeout); /// <summary>
/// 获取项
/// </summary>
/// <param name="lockRecord"></param>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="locked"></param>
/// <param name="lockAge"></param>
/// <param name="lockId"></param>
/// <param name="actions"></param>
/// <returns></returns>
SessionStateStoreData GetItem(bool lockRecord, System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions); /// <summary>
/// 释放项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="lockId"></param>
void ReleaseItem(System.Web.HttpContext context, string id, object lockId); /// <summary>
/// 移除项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="lockId"></param>
void RemoveItem(System.Web.HttpContext context, string id, object lockId); /// <summary>
/// 重设项的超时时间
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
void ResetItemTimeout(System.Web.HttpContext context, string id); /// <summary>
/// 设置并释放项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="lockId"></param>
/// <param name="newItem"></param>
void SetAndReleaseItem(System.Web.HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem);
}

创建一个ISessionStateStoreBehavior,将涉及Session存储的方法公开。

/// <summary>
/// Session驱动行为工厂
/// </summary>
class SessionProviderBehaviorFactory
{
/// <summary>
/// 当前Session状态存储行为实例
/// </summary>
static ISessionStateStoreBehavior currentSessionStateStoreBehavior; /// <summary>
/// 创建Session状态存储行为实例
/// </summary>
/// <returns></returns>
public static ISessionStateStoreBehavior CreateSessionStateStoreBehaviorInstance()
{
if (currentSessionStateStoreBehavior == null)
{
var types = Assembly.GetExecutingAssembly().GetTypes().Where(t => !t.IsAbstract && t.GetInterface(typeof(ISessionStateStoreBehavior).Name) != null);
var currentType = types.FirstOrDefault(t => t.Name == string.Format("{0}SessionStateStoreBehavior", SessionProviderConfigurationSectionHandler.SessionProviderSettings.SessionStateStoreProviderBehaviorName));
if (currentType != null)
{
currentSessionStateStoreBehavior = (ISessionStateStoreBehavior)Activator.CreateInstance(currentType);
}
} return currentSessionStateStoreBehavior;
}
}

通过工厂得到当前应用程序域下的继承了ISessionStateStoreBehavior接口的所有实现类,并读取配置得到当前实例。

基于MongoDB的一个行为实现

/// <summary>
/// 基于Mongo的Session状态存储行为
/// </summary>
public class MongoSessionStateStoreBehavior : SessionStateStoreBehaviorBase, ISessionStateStoreBehavior
{
/// <summary>
/// 构造函数
/// </summary>
public MongoSessionStateStoreBehavior()
: base()
{
if (collection == null)
{
collection = GetMongoDBCollection();
var expiresKey = IndexKeys.Ascending("Expires");
var options = IndexOptions.SetTimeToLive(base.SessionStateSection.Timeout);
collection.EnsureIndex(expiresKey, options);
collection.EnsureIndex("LockId", "Locked");
}
} static MongoCollection<MongoDBSessionDo> collection; /// <summary>
/// 获取Mongo集合
/// </summary>
/// <returns></returns>
static MongoCollection<MongoDBSessionDo> GetMongoDBCollection()
{
var url = new MongoUrl(SessionProviderConfigurationSectionHandler.SessionProviderSettings.StorageConnectionString);
var client = new MongoClient(url);
var database = client.GetServer().GetDatabase(url.DatabaseName, WriteConcern.Unacknowledged);
return database.GetCollection<MongoDBSessionDo>(ConfigSection.SessionProviderConfigurationSectionHandler.SessionProviderSettings.SessionProfix);
} /// <summary>
/// 创建未初始化项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="timeout"></param>
public void CreateUninitializedItem(System.Web.HttpContext context, string id, int timeout)
{
var session = new MongoDBSessionDo()
{
SessionId = id,
Created = DateTime.Now,
Expires = DateTime.Now.AddMinutes(base.SessionStateSection.Timeout.TotalMinutes),
LockDate = DateTime.Now,
LockId = ,
Timeout = timeout,
Locked = false,
Flags = (int)SessionStateActions.InitializeItem,
};
collection.Save(session);
SetSessionIdCookieExpires(context, session.Expires);
} /// <summary>
/// 获取项
/// </summary>
/// <param name="lockRecord"></param>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="locked"></param>
/// <param name="lockAge"></param>
/// <param name="lockId"></param>
/// <param name="actions"></param>
/// <returns></returns>
public System.Web.SessionState.SessionStateStoreData GetItem(bool lockRecord, System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out System.Web.SessionState.SessionStateActions actions)
{
var item = default(SessionStateStoreData);
lockAge = TimeSpan.Zero;
lockId = null;
locked = false;
actions = ; bool foundRecord = false;
bool deleteData = false; var session = collection.AsQueryable().FirstOrDefault(s => s.SessionId == id); if (lockRecord)
{
locked = session != null && !session.Locked && session.Expires > DateTime.Now;
} if (session != null)
{
if (session.Expires < DateTime.Now)
{
locked = false;
deleteData = true;
}
else
{
foundRecord = true;
}
} if (deleteData)
{
collection.Remove(Query.EQ("_id", id));
} if (!foundRecord)
locked = false; if (foundRecord && !locked)
{
lockId = lockId == null ? : (int)lockId + ;
collection.Update(Query.EQ("_id", id), Update.Set("LockId", (int)lockId).Set("Flags", (int)SessionStateActions.None));
var timeout = actions == SessionStateActions.InitializeItem ? (int)base.SessionStateSection.Timeout.TotalMinutes : session.Timeout;
var sessionStateItemCollection = actions == SessionStateActions.InitializeItem ? new SessionStateItemCollection() : Helper.Deserialize(session.SessionItems);
item = new SessionStateStoreData(sessionStateItemCollection, SessionStateUtility.GetSessionStaticObjects(context), timeout);
} return item;
} /// <summary>
/// 释放项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="lockId"></param>
public void ReleaseItem(System.Web.HttpContext context, string id, object lockId)
{
var expires = DateTime.Now.AddMinutes(base.SessionStateSection.Timeout.TotalMinutes);
collection.Update(Query.And(Query.EQ("LockId", int.Parse(lockId.ToString())), Query.EQ("_id", id)), Update.Set("Locked", false).Set("Expires", expires));
SetSessionIdCookieExpires(context, expires);
} /// <summary>
/// 移除项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="lockId"></param>
public void RemoveItem(System.Web.HttpContext context, string id, object lockId)
{
collection.Remove(Query.And(Query.EQ("LockId", int.Parse(lockId.ToString())), Query.EQ("_id", id)));
SetSessionIdCookieExpires(context, DateTime.Now.AddDays(-), true);
} /// <summary>
/// 重设项超时时间
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
public void ResetItemTimeout(System.Web.HttpContext context, string id)
{
var expires = DateTime.Now.AddMinutes(base.SessionStateSection.Timeout.TotalMinutes);
collection.Update(Query.And(Query.EQ("_id", id)), Update.Set("Expires", expires));
SetSessionIdCookieExpires(context, expires);
} /// <summary>
/// 设置并释放项
/// </summary>
/// <param name="context"></param>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="lockId"></param>
/// <param name="newItem"></param>
public void SetAndReleaseItem(System.Web.HttpContext context, string id, System.Web.SessionState.SessionStateStoreData item, object lockId, bool newItem)
{
var session = default(MongoDBSessionDo);
if (newItem)
{
session = new MongoDBSessionDo();
session.SessionId = id;
session.Created = DateTime.Now;
session.Expires = DateTime.Now.AddMinutes(base.SessionStateSection.Timeout.TotalMinutes);
session.LockDate = DateTime.Now;
session.LockId = ;
session.Timeout = item.Timeout;
session.Locked = false;
session.Flags = (int)SessionStateActions.None;
session.SessionItems = Helper.Serialize((SessionStateItemCollection)item.Items);
}
else
{
session = collection.FindOne(Query.And(Query.EQ("_id", id), Query.EQ("LockId", int.Parse(lockId.ToString()))));
session.Expires = DateTime.Now.AddMinutes(item.Timeout);
session.SessionItems = Helper.Serialize((SessionStateItemCollection)item.Items);
session.Locked = false;
}
collection.Save(session);
SetSessionIdCookieExpires(context, session.Expires);
}
}

配置相关

<configSections>
<section name="SessionProviderSettings" type="CustomSessionDemo.SessionProviderConfigurationSectionHandler, CustomSessionDemo"/>
</configSections> <SessionProviderSettings>
<SessionProfix>Test</SessionProfix>
<IsSynchronousSessionIdTimeout>true</IsSynchronousSessionIdTimeout>
<SessionStateStoreProviderBehaviorName>Mongo</SessionStateStoreProviderBehaviorName>
<StorageConnectionString>mongodb://192.168.1.43:27017/TestSessionDB</StorageConnectionString>
</SessionProviderSettings> <system.web>
<sessionState mode="Custom" customProvider="SessionProvider" sessionIDManagerType="CustomSessionDemo.CustomSessionIDManager" timeout="">
<providers>
<add name="SessionProvider" type="CustomSessionDemo.CustomSessionStateStoreProvider, CustomSessionDemo"/>
</providers>
</sessionState>

执行效果

可灵活扩展的自定义Session状态存储驱动

可灵活扩展的自定义Session状态存储驱动

可灵活扩展的自定义Session状态存储驱动的更多相关文章

  1. 自定义session的存储机制

    <?php class MSession implements SessionHandlerInterface{ // reids 对象 protected $handler = null; / ...

  2. ThinkPHP - session 数据库存储驱动

    命名格式: Session + 驱动名称 + .class.php 所有的方法要有,但不一定要实现. <?php /** * @category Extend * @package Extend ...

  3. Session 知识点再整理(二) 自定义 Session 存储机制

    对于访问量大的网站,用默认的 Session 存储方式(以文件存储)不适合,因为文件的 I/O 开销会非常大,另外 Session 机制本身使 Session 不能跨机访问,在 Web 集群中无法达到 ...

  4. Android实训案例(八)——单机五子棋游戏,自定义棋盘,线条,棋子,游戏逻辑,游戏状态存储,再来一局

    Android实训案例(八)--单机五子棋游戏,自定义棋盘,线条,棋子,游戏逻辑,游戏状态存储,再来一局 阿法狗让围棋突然就被热议了,鸿洋大神也顺势出了篇五子棋单机游戏的视频,我看到了就像膜拜膜拜,就 ...

  5. Web APi 2&period;0优点和特点?在Web APi中如何启动Session状态?

    前言 曾几何时,微软基于Web服务技术给出最流行的基于XML且以扩展名为.asmx结尾的Web Service,此服务在.NET Framework中风靡一时同时也被.NET业界同仁所青睐,几年后在此 ...

  6. ASP&period;net 中关于Session的存储信息及其它方式存储信息的讨论与总结

    通过学习和实践笔者总结一下Session 的存储方式.虽然里面的理论众所周知,但是我还是想记录并整理一下.作为备忘录吧.除了ASP.net通过Web.config配置的方式,还有通过其它方式来存储的方 ...

  7. session的存储方式和配置

    Session又称为会话状态,是Web系统中最常用的状态,用于维护和当前浏览器实例相关的一些信息.我们控制用户去权限中经常用到Session来存储用户状态,这篇文章会讲下Session的存储方式.在w ...

  8. Tornado之自定义session

      面向对象基础 面向对象中通过索引的方式访问对象,需要内部实现 __getitem__ .__delitem__.__setitem__方法 #!/usr/bin/env python # -*- ...

  9. Azure Redis Cache作为ASP&period;NET Session状态提供程序

    从上一篇博客<使用Azure Redis Cache>我们已经可以创建并使用Redis Cache为我们服务了. 作为Web开发者,我们都知道Session状态默认是保存在内存中的,它的优 ...

随机推荐

  1. 用javascript动态创建并提交表单form,表格table

    <script> //helper function to create the formfunction getNewSubmitForm(){ var submitForm = doc ...

  2. Android中Parcelable接口的使用

    在做开发的过程中,序列化是非常常见的.比如要将对象保存本地磁盘或者在网络上传输等.实现序列化有两种方式,一种是实现Serializable接口,第二种是实现Parcelable. Serializab ...

  3. git配置ssh

    $ git config --global user.name "yourname"$ git config --global user.email "youremail ...

  4. JavaWeb工程中web&period;xml基本配置(转载学习)

    一.理论准备 先说下我记得xml规则,必须有且只有一个根节点,大小写敏感,标签不嵌套,必须配对. web.xml是不是必须的呢?不是的,只要你不用到里面的配置信息就好了,不过在大型web工程下使用该文 ...

  5. 连接oracle数据库

    一.连接oracle数据库 一.windows环境 oracle windows客户端下载地址:http://www.oracle.com/technetwork/topics/winx64soft- ...

  6. android用OkHttp和okio包通信的坑--气死我了

    今天新建了个项目,想要用用okhttp包来实现Android和tomcat的通信, 于是就根据记忆,把以前可以用的代码复制过来了,然后呢,出现这个.... 图有点大,不知到怎么调小 很莫名其妙,我看了 ...

  7. Apollo的Oracle适配

    Apollo的Oracle适配改动   这几天工作需要使用Apollo配置中心.Apollo唯一的依赖是MySQL数据库,然而公司只有Oracle数据库资源.这里有一个Oracle适配改动的分支,但是 ...

  8. 【转】让Entity Framework不再私闯sys&period;databases

    这里的“私闯sys.databases”是指Entity Framework默认发起的查询:SELECT Count(*) FROM sys.databases WHERE [name]=N'数据库名 ...

  9. 《ArcGIS Runtime SDK for Android开发笔记》——(13)、图层扩展方式加载Google地图

    1.前言 http://mt2.google.cn/vt/lyrs=m@225000000&hl=zh-CN&gl=cn&x=420&y=193&z=9&amp ...

  10. 学习Microsoft SQL Server 2008技术内幕:T-SQL语法基础

    第 2 章: 单表查询 use TSQLFundamentals2008; select * from Sales.orders; select empid, year(orderdate) as o ...