using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using System.Web.SessionState;
using ServiceStack.Redis;
using System.Configuration;
using System.Configuration.Provider;
using System.Web.Configuration;
using System.IO; namespace RedisProvider.SessionProvider
{ #region Session Item Model
public class SessionItem
{ #region Properties
public DateTime CreatedAt { get; set; }
public DateTime LockDate { get; set; }
public int LockID { get; set; }
public int Timeout { get; set; }
public bool Locked { get; set; }
public string SessionItems { get; set; }
public int Flags { get; set; }
#endregion Properties }
#endregion Session Item Model public class CustomServiceProvider : System.Web.SessionState.SessionStateStoreProviderBase, IDisposable
{ #region Properties
private string ApplicationName
{
get
{
if (ConfigurationManager.AppSettings.AllKeys.Contains("Application.Name"))
{
return ConfigurationManager.AppSettings["Application.Name"];
} return string.Empty;
}
} private RedisClient RedisSessionClient
{
get
{ if (!string.IsNullOrEmpty(this.redisPassword))
{
return new RedisClient(this.redisServer, this.redisPort, this.redisPassword);
} return new RedisClient(this.redisServer, this.redisPort);
}
} private string redisServer = "localhost";
private int redisPort = ;
private string redisPassword = string.Empty;
private SessionStateSection sessionStateConfig = null;
private bool writeExceptionsToLog = false;
#endregion Properties #region Private Methods
/// <summary>
/// Prepends the application name to the redis key if one exists. Querying by application name is recommended for session
/// </summary>
/// <param name="id">The session id</param>
/// <returns>Concatenated string applicationname:sessionkey</returns>
private string RedisKey(string id)
{
return string.Format("{0}{1}", !string.IsNullOrEmpty(this.ApplicationName) ? this.ApplicationName + ":" : "", id);
}
#endregion Private Methods #region Constructor
public CustomServiceProvider()
{ }
#endregion Constructor #region Overrides
public override void Dispose()
{ } public override void Initialize(string name, NameValueCollection config)
{ // Initialize values from web.config.
if (config == null)
{
throw new ArgumentNullException("config");
} if (name == null || name.Length == )
{
name = "RedisSessionStateStore";
} if (String.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Redis Session State Provider");
} // Initialize the abstract base class.
base.Initialize(name, config); // Get <sessionState> configuration element.
Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
sessionStateConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState"); if (config["writeExceptionsToEventLog"] != null)
{
if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
this.writeExceptionsToLog = true;
} if (config["server"] != null)
{
this.redisServer = config["server"];
} if (config["port"] != null)
{
int.TryParse(config["port"], out this.redisPort);
} if (config["password"] != null)
{
this.redisPassword = config["password"];
}
} public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
{
return true;
} public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
{
using (RedisClient client = this.RedisSessionClient)
{
// Serialize the SessionStateItemCollection as a string.
string sessionItems = Serialize((SessionStateItemCollection)item.Items); try
{
if (newItem)
{
SessionItem sessionItem = new SessionItem();
sessionItem.CreatedAt = DateTime.UtcNow;
sessionItem.LockDate = DateTime.UtcNow;
sessionItem.LockID = ;
sessionItem.Timeout = item.Timeout;
sessionItem.Locked = false;
sessionItem.SessionItems = sessionItems;
sessionItem.Flags = ; client.Set<SessionItem>(this.RedisKey(id), sessionItem, DateTime.UtcNow.AddMinutes(item.Timeout));
}
else
{
SessionItem currentSessionItem = client.Get<SessionItem>(this.RedisKey(id));
if (currentSessionItem != null && currentSessionItem.LockID == (int?)lockId)
{
currentSessionItem.Locked = false;
currentSessionItem.SessionItems = sessionItems;
client.Set<SessionItem>(this.RedisKey(id), currentSessionItem, DateTime.UtcNow.AddMinutes(item.Timeout));
}
}
}
catch (Exception e)
{
throw e;
}
}
} public override SessionStateStoreData GetItemExclusive(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
{
return GetSessionStoreItem(true, context, id, out locked, out lockAge, out lockId, out actions);
} public override SessionStateStoreData GetItem(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags)
{
return GetSessionStoreItem(false, context, id, out locked, out lockAge, out lockId, out actionFlags);
} private SessionStateStoreData GetSessionStoreItem(bool lockRecord,
HttpContext context,
string id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags)
{ // Initial values for return value and out parameters.
SessionStateStoreData item = null;
lockAge = TimeSpan.Zero;
lockId = null;
locked = false;
actionFlags = ; // String to hold serialized SessionStateItemCollection.
string serializedItems = ""; // Timeout value from the data store.
int timeout = ; using (RedisClient client = this.RedisSessionClient)
{
try
{
if (lockRecord)
{
locked = false;
SessionItem currentItem = client.Get<SessionItem>(this.RedisKey(id)); if (currentItem != null)
{
// If the item is locked then do not attempt to update it
if (!currentItem.Locked)
{
currentItem.Locked = true;
currentItem.LockDate = DateTime.UtcNow;
client.Set<SessionItem>(this.RedisKey(id), currentItem, DateTime.UtcNow.AddMinutes(sessionStateConfig.Timeout.TotalMinutes));
}
else
{
locked = true;
}
}
} SessionItem currentSessionItem = client.Get<SessionItem>(this.RedisKey(id)); if (currentSessionItem != null)
{
serializedItems = currentSessionItem.SessionItems;
lockId = currentSessionItem.LockID;
lockAge = DateTime.UtcNow.Subtract(currentSessionItem.LockDate);
actionFlags = (SessionStateActions)currentSessionItem.Flags;
timeout = currentSessionItem.Timeout;
}
else
{
locked = false;
} if (currentSessionItem != null && !locked)
{
// Delete the old item before inserting the new one
client.Remove(this.RedisKey(id)); lockId = (int?)lockId + ;
currentSessionItem.LockID = lockId != null ? (int)lockId : ;
currentSessionItem.Flags = ; client.Set<SessionItem>(this.RedisKey(id), currentSessionItem, DateTime.UtcNow.AddMinutes(sessionStateConfig.Timeout.TotalMinutes)); // If the actionFlags parameter is not InitializeItem,
// deserialize the stored SessionStateItemCollection.
if (actionFlags == SessionStateActions.InitializeItem)
{
item = CreateNewStoreData(context, );
}
else
{
item = Deserialize(context, serializedItems, timeout);
}
}
} catch (Exception e)
{
throw e;
}
} return item;
} public override void ReleaseItemExclusive(HttpContext context, string id, object lockId)
{ using (RedisClient client = this.RedisSessionClient)
{
SessionItem currentSessionItem = client.Get<SessionItem>(this.RedisKey(id)); if (currentSessionItem != null && (int?)lockId == currentSessionItem.LockID)
{
currentSessionItem.Locked = false;
client.Set<SessionItem>(this.RedisKey(id), currentSessionItem, DateTime.UtcNow.AddMinutes(sessionStateConfig.Timeout.TotalMinutes));
}
}
} public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
{
using (RedisClient client = this.RedisSessionClient)
{
// Delete the old item before inserting the new one
client.Remove(this.RedisKey(id));
}
} public override void CreateUninitializedItem(HttpContext context, string id, int timeout)
{
using (RedisClient client = this.RedisSessionClient)
{
SessionItem sessionItem = new SessionItem();
sessionItem.CreatedAt = DateTime.Now.ToUniversalTime();
sessionItem.LockDate = DateTime.Now.ToUniversalTime();
sessionItem.LockID = ;
sessionItem.Timeout = timeout;
sessionItem.Locked = false;
sessionItem.SessionItems = string.Empty;
sessionItem.Flags = ; client.Set<SessionItem>(this.RedisKey(id), sessionItem, DateTime.UtcNow.AddMinutes(timeout));
}
} public override SessionStateStoreData CreateNewStoreData(System.Web.HttpContext context, int timeout)
{
return new SessionStateStoreData(new SessionStateItemCollection(),
SessionStateUtility.GetSessionStaticObjects(context),
timeout);
} public override void ResetItemTimeout(HttpContext context, string id)
{ using (RedisClient client = this.RedisSessionClient)
{
try
{
// TODO :: GET THIS VALUE FROM THE CONFIG
client.ExpireEntryAt(id, DateTime.UtcNow.AddMinutes(sessionStateConfig.Timeout.TotalMinutes));
}
catch (Exception e)
{
throw e;
}
}
} public override void InitializeRequest(HttpContext context)
{
// Was going to open the redis connection here but sometimes I had 5 connections open at one time which was strange
} public override void EndRequest(HttpContext context)
{
this.Dispose();
}
#endregion Overrides #region Serialization
/// <summary>
/// Serialize is called by the SetAndReleaseItemExclusive method to
/// convert the SessionStateItemCollection into a Base64 string to
/// be stored in MongoDB.
/// </summary>
private string Serialize(SessionStateItemCollection items)
{
using (MemoryStream ms = new MemoryStream())
using (BinaryWriter writer = new BinaryWriter(ms))
{
if (items != null)
items.Serialize(writer); writer.Close(); return Convert.ToBase64String(ms.ToArray());
}
} private SessionStateStoreData Deserialize(HttpContext context, string serializedItems, int timeout)
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(serializedItems)))
{
SessionStateItemCollection sessionItems = new SessionStateItemCollection(); if (ms.Length > )
{
using (BinaryReader reader = new BinaryReader(ms))
{
sessionItems = SessionStateItemCollection.Deserialize(reader);
}
} return new SessionStateStoreData(sessionItems,
SessionStateUtility.GetSessionStaticObjects(context),
timeout);
}
}
#endregion Serialization
}
}
<system.web
<sessionState timeout="" mode="Custom" customProvider="RedisSessionStateProvider" cookieless="false">
<providers>
<add name="RedisSessionStateProvider" writeexceptionstoeventlog="false" type="RedisProvider.SessionProvider.CustomServiceProvider" server="192.168.1.118" port="" password="admin"></add>
</providers>
</sessionState>
</system.web>

Redis提供商配置ASP.NET会话状态的更多相关文章

  1. ASP.NET 会话状态的模式

    ASP.NET 会话状态为会话数据提供了几个不同的存储选项.每个选项都通过一个 SessionStateMode 枚举值进行识别.如下列表中描述了可用的会话状态模式: InProc 模式:把会话状态存 ...

  2. Azure Redis 缓存的 ASP.NET 会话状态提供程序

    Azure Redis Cache 提供了一个会话状态提供程序,你可以使用其在缓存中(而不是内存中或在 SQL Server 数据库中)存储会话状态.要使用缓存会话状态提供程序,先首先配置缓存,然后使 ...

  3. centos 安装php-fpm , nginx二级域名配置 ,但为什么必须要 域名提供商 哪里解析新的二级域名一下 才能用呢?

    yum -y install php-fpm php-mysql(当然还有其它扩展) /etc/init.d/php-fpm restart (重启php-fpm) /etc/php.ini (php ...

  4. 第22章 使用外部身份提供商登录 - Identity Server 4 中文文档(v1.0.0)

    ASP.NET Core有一种灵活的方式来处理外部身份验证.这涉及几个步骤. 注意 如果您使用的是ASP.NET Identity,则会隐藏许多基础技术细节.建议您还阅读Microsoft 文档并执行 ...

  5. Cloud Native Weekly | 华为云抢先发布Redis5.0,红帽宣布收购混合云提供商 NooBaa

    1——华为云抢先发布Redis5.0 2——DigitalOcean K8s服务正式上线 3——红帽宣布收购混合云提供商 NooBaa 4——微软发布多项 Azure Kubernetes 服务更新 ...

  6. 在Linux(Ubuntu/openSUSE/CentOS)下配置ASP.NET(Apache + Mono)

    [题外话] 闲的无聊竟然想尝试测试自己做的项目在不同操作系统上的性能表现,所以决定试试在Linux上部署Apache和Mono的环境.由于平时很少接触Linux,所以从网上找了几篇文章(附在相关链接中 ...

  7. redis的安装配置

    主要讲下redis的安装配置,以及以服务的方式启动redis 1.下载最新版本的redis-3.0.7  到http://redis.io/download中下载最新版的redis-3.0.7 下载后 ...

  8. 用"hosting.json"配置ASP.NET Core站点的Hosting环境

    通常我们在 Prgram.cs 中使用硬编码的方式配置 ASP.NET Core 站点的 Hosting 环境,最常用的就是 .UseUrls() . public class Program { p ...

  9. redis的主从复制配置

    redis的主从复制配置 一.     原理 Redis的主从复制功能非常强大,一个master可以拥有多个slave,而一个slave又可以拥有多个slave,如此下去,形成了强大的多级服务器集群架 ...

随机推荐

  1. luogu P3919 【模板】可持久化数组(可持久化线段树/平衡树)

    As you see // luogu-judger-enable-o2 #include<cstdio> #include<cstring> #include<algo ...

  2. [51nod1538]一道难题

    先观察一下题目给出的式子:对所有满足$\begin{align*}\sum\limits_{i=1}^na_ib_i=m\end{align*}$的$b_{1\cdots n}$,计算$\begin{ ...

  3. [Contest20180316]Game

    这题有一个结论:如果他是最强的(⑨),那么线段树最优,如果他是最弱的,那么链状树最优 严格证明可能挺困难,感性理解就是公平赛制让强的人容易赢,极度不公平的赛制能让弱的人有机会反杀 所以我们只改他的能力 ...

  4. [CF441E]Valera and Number

    题意:给定$x,k,p$和一份伪代码,伪代码大致是循环$k$次,每次有$p\%$的概率把$x$乘$2$,有$(100-p)\%$的概率把$x$加$1$,问最后在二进制下$x$的末尾期望$0$个数 鸽了 ...

  5. Java高级架构师(一)第03节:多模块多Web应用合并War包

    多模块.多Web应用合并war包 在日常的系统开发中,如果担心各个系统的资源同名覆盖,可以在总的War模块下放置一份最终的资源. 将版本号改成9.1.0.v20131115,ok 在Idea中的Mav ...

  6. Xamarin.Forms 调用 腾讯地图SDK

    Xamarin.Forms研究了好一段时间了,最近一直在学习中,想尝试一下调用其他的SDK,就如腾讯地图SDK(申请容易). 完成此次项目得感谢以下链接: http://www.cnblogs.com ...

  7. linux上虚拟显示器和火狐浏览器的使用学习记录

    Ubuntu 14.04 sudo apt-get firefox sudo apt-get install python-pip sudo apt-get install xvfb# xserver ...

  8. 爬虫扒下 bilibili 视频信息

    B站算是对爬虫非常非常友好的网站啦! 修改转载已取得腾讯云授权 在以上两篇文章中我们已经在腾讯云服务器上搭建好了 Python 爬虫环境了,下一步就是在云服务器上爬上我们的爬虫,抓取我们想要的数据: ...

  9. Gitlab安装部署及基础操作

      环境说明 系统版本 CentOS 7.2 x86_64(较新版本的gitlab集成了更多功能,顺利运行起来的硬件要求较高,这里给了3G内存) 软件版本 gitlab-ce-10.8.4 GitLa ...

  10. C 实现strcmp,strcpy,strcat函数

    基于C语言的strcmp,strcpy,strcat函数的实现.C语言是一个程序猿的基础,一定要重视. char* strcat ( char * dst , const char * src ) { ...