热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

解读ASP.NET5&MVC6系列教程(8):Session与Caching

这篇文章主要介绍了ASP.NET5中的Session与Caching配置和使用,需要的朋友可以参考下

在之前的版本中,Session存在于System.Web中,新版ASP.NET 5中由于不在依赖于System.Web.dll库了,所以相应的,Session也就成了ASP.NET 5中一个可配置的模块(middleware)了。

配置启用Session

ASP.NET 5中的Session模块存在于Microsoft.AspNet.Session类库中,要启用Session,首先需要在project.json中的dependencies节点中添加如下内容:

"Microsoft.AspNet.Session": "1.0.0-beta3"

然后在ConfigureServices中添加Session的引用(并进行配置):

services.AddCaching(); // 这两个必须同时添加,因为Session依赖于Caching
services.AddSession();
//services.ConfigureSession(null); 可以在这里配置,也可以再后面进行配置

最后在Configure方法中,开启使用Session的模式,如果在上面已经配置过了,则可以不再传入配置信息,否则还是要像上面的配置信息一样,传入Session的配置信息,代码如下:

app.UseInMemorySession(configure:s => { s.IdleTimeout = TimeSpan.FromMinutes(30); });
//app.UseSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(30); });
//app.UseInMemorySession(null, null); //开启内存Session
//app.UseDistributedSession(null, null);//开启分布式Session,也即持久化Session
//app.UseDistributedSession(new RedisCache(new RedisCacheOptions() { COnfiguration= "localhost" }));

对于UseInMemorySession方法,接收2个可选参数,分别是:IMemoryCache可用于修改Session数据的默认保存地址;Action委托则可以让你修改默认选项,比如Session COOKIE的路径、默认的过期时间等。本例中,我们修改默认过期时间为30分钟。

注意:该方法必须在app.UseMvc之前调用,否则在Mvc里获取不到Session,而且会出错。

获取和设置Session

获取和设置Session对象,一般是在Controller的action里通过this.Context.Session来获取的,其获取的是一个基于接口ISessionCollection的实例。该接口可以通过索引、Set、TryGetValue等方法进行Session值的获取和设置,但我们发现在获取和设置Session的时候,我们只能使用byte[]类型,而不能像之前版本的Session一样可以设置任意类型的数据。原因是因为,新版本的Session要支持在远程服务器上存储,就需要支持序列化,所以才强制要求保存为byte[]类型。所以我们在保存Session的时候,需要将其转换为byte[]才能进行保存,并且获取以后要再次将byte[]转换为自己的原有的类型才行。这种形式太麻烦了,好在微软在Microsoft.AspNet.Http命名空间(所属Microsoft.AspNet.Http.Extensions.dll中)下,为我们添加了几个扩展方法,分别用于设置和保存byte[]类型、int类型、以及string类型,代码如下:

public static byte[] Get(this ISessionCollection session, string key);
public static int? GetInt(this ISessionCollection session, string key);
public static string GetString(this ISessionCollection session, string key);
public static void Set(this ISessionCollection session, string key, byte[] value);
public static void SetInt(this ISessionCollection session, string key, int value);
public static void SetString(this ISessionCollection session, string key, string value);

所以,在Controller里引用Microsoft.AspNet.Http命名空间以后,我们就可以通过如下代码进行Session的设置和获取了:

Context.Session.SetString("Name", "Mike");
Context.Session.SetInt("Age", 21);

ViewBag.Name = Context.Session.GetString("Name");
ViewBag.Age = Context.Session.GetInt("Age");

自定义类型的Session设置和获取

前面我们说了,要保存自定义类型的Session,需要将其类型转换成byte[]数组才行,在本例中,我们对bool类型的Session数据进行设置和获取的代码,示例如下:

public static class SessionExtensions
{
 public static bool? GetBoolean(this ISessionCollection session, string key)
 {
  var data = session.Get(key);
  if (data == null)
  {
   return null;
  }
  return BitConverter.ToBoolean(data, 0);
 } 

 public static void SetBoolean(this ISessionCollection session, string key, bool value)
 {
  session.Set(key, BitConverter.GetBytes(value));
 }
}

定义bool类型的扩展方法以后,我们就可以像SetInt/GetInt那样进行使用了,示例如下:

Context.Session.SetBoolean("Liar", true);
ViewBag.Liar = Context.Session.GetBoolean("Liar");

另外,ISessionCollection接口上还提供了Remove(string key)和Clear()两个方法分别用于删除某个Session值和清空所有的Session值的功能。但同时也需要注意,该接口并没提供之前版本中的Abandon方法功能。

基于Redis的Session管理

使用分布式Session,其主要工作就是将Session保存的地方从原来的内存换到分布式存储上,本节,我们以Redis存储为例来讲解分布式Session的处理。

先查看使用分布式Session的扩展方法,示例如下,我们可以看到,其Session容器需要是一个支持IDistributedCache的接口示例。

public static IApplicationBuilder UseDistributedSession([NotNullAttribute]this IApplicationBuilder app, IDistributedCache cache, Action cOnfigure= null);

该接口是缓存Caching的通用接口,也就是说,只要我们实现了缓存接口,就可以将其用于Session的管理。进一步查看该接口发现,该接口中定义的Set方法还需要实现一个ICacheContext类型的缓存上下文(以便在调用的时候让其它程序进行委托调用),接口定义分别如下:

public interface IDistributedCache
{
 void Connect();
 void Refresh(string key);
 void Remove(string key);
 Stream Set(string key, object state, Action create);
 bool TryGetValue(string key, out Stream value);
}

public interface ICacheContext
{
 Stream Data { get; }
 string Key { get; }
 object State { get; }

 void SetAbsoluteExpiration(TimeSpan relative);
 void SetAbsoluteExpiration(DateTimeOffset absolute);
 void SetSlidingExpiration(TimeSpan offset);
}

接下来,我们基于Redis来实现上述功能,创建RedisCache类,并继承IDistributedCache,引用StackExchange.Redis程序集,然后实现IDistributedCache接口的所有方法和属性,代码如下:

using Microsoft.Framework.Cache.Distributed;
using Microsoft.Framework.OptionsModel;
using StackExchange.Redis;
using System;
using System.IO;

namespace Microsoft.Framework.Caching.Redis
{
 public class RedisCache : IDistributedCache
 {
  // KEYS[1] = = key
  // ARGV[1] = absolute-expiration - ticks as long (-1 for none)
  // ARGV[2] = sliding-expiration - ticks as long (-1 for none)
  // ARGV[3] = relative-expiration (long, in seconds, -1 for none) - Min(absolute-expiration - Now, sliding-expiration)
  // ARGV[4] = data - byte[]
  // this order should not change LUA script depends on it
  private const string SetScript = (@"
    redis.call('HMSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4])
    if ARGV[3] ~= '-1' then
     redis.call('EXPIRE', KEYS[1], ARGV[3]) 
    end
    return 1");
  private const string AbsoluteExpiratiOnKey= "absexp";
  private const string SlidingExpiratiOnKey= "sldexp";
  private const string DataKey = "data";
  private const long NotPresent = -1;

  private ConnectionMultiplexer _connection;
  private IDatabase _cache;

  private readonly RedisCacheOptions _options;
  private readonly string _instance;

  public RedisCache(IOptions optionsAccessor)
  {
   _optiOns= optionsAccessor.Options;
   // This allows partitioning a single backend cache for use with multiple apps/services.
   _instance = _options.InstanceName ?? string.Empty;
  }

  public void Connect()
  {
   if (_cOnnection== null)
   {
    _cOnnection= ConnectionMultiplexer.Connect(_options.Configuration);
    _cache = _connection.GetDatabase();
   }
  }

  public Stream Set(string key, object state, Action create)
  {
   Connect();

   var cOntext= new CacheContext(key) { State = state };
   create(context);
   var value = context.GetBytes();
   var result = _cache.ScriptEvaluate(SetScript, new RedisKey[] { _instance + key },
    new RedisValue[]
    {
     context.AbsoluteExpiration?.Ticks ?? NotPresent,
     context.SlidingExpiration?.Ticks ?? NotPresent,
     context.GetExpirationInSeconds() ?? NotPresent,
     value
    });
   // TODO: Error handling
   return new MemoryStream(value, writable: false);
  }

  public bool TryGetValue(string key, out Stream value)
  {
   value = GetAndRefresh(key, getData: true);
   return value != null;
  }

  public void Refresh(string key)
  {
   var ignored = GetAndRefresh(key, getData: false);
  }

  private Stream GetAndRefresh(string key, bool getData)
  {
   Connect();

   // This also resets the LRU status as desired.
   // TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
   RedisValue[] results;
   if (getData)
   {
    results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey);
   }
   else
   {
    results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey);
   }
   // TODO: Error handling
   if (results.Length >= 2)
   {
    // Note we always get back two results, even if they are all null.
    // These operations will no-op in the null scenario.
    DateTimeOffset? absExpr;
    TimeSpan? sldExpr;
    MapMetadata(results, out absExpr, out sldExpr);
    Refresh(key, absExpr, sldExpr);
   }
   if (results.Length >= 3 && results[2].HasValue)
   {
    return new MemoryStream(results[2], writable: false);
   }
   return null;
  }

  private void MapMetadata(RedisValue[] results, out DateTimeOffset? absoluteExpiration, out TimeSpan? slidingExpiration)
  {
   absoluteExpiration = null;
   slidingExpiration = null;
   var absoluteExpiratiOnTicks= (long?)results[0];
   if (absoluteExpirationTicks.HasValue && absoluteExpirationTicks.Value != NotPresent)
   {
    absoluteExpiration = new DateTimeOffset(absoluteExpirationTicks.Value, TimeSpan.Zero);
   }
   var slidingExpiratiOnTicks= (long?)results[1];
   if (slidingExpirationTicks.HasValue && slidingExpirationTicks.Value != NotPresent)
   {
    slidingExpiration = new TimeSpan(slidingExpirationTicks.Value);
   }
  }

  private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr)
  {
   // Note Refresh has no effect if there is just an absolute expiration (or neither).
   TimeSpan? expr = null;
   if (sldExpr.HasValue)
   {
    if (absExpr.HasValue)
    {
     var relExpr = absExpr.Value - DateTimeOffset.Now;
     expr = relExpr <= sldExpr.Value &#63; relExpr : sldExpr;
    }
    else
    {
     expr = sldExpr;
    }
    _cache.KeyExpire(_instance + key, expr);
    // TODO: Error handling
   }
  }

  public void Remove(string key)
  {
   Connect();

   _cache.KeyDelete(_instance + key);
   // TODO: Error handling
  }
 }
}

在上述代码中,我们使用了自定义类RedisCacheOptions作为Redis的配置信息类,为了实现基于POCO的配置定义,我们还继承了IOptions接口,该类的定义如下:

public class RedisCacheOptions : IOptions
{
 public string Configuration { get; set; }

 public string InstanceName { get; set; }

 RedisCacheOptions IOptions.Options
 {
  get { return this; }
 }

 RedisCacheOptions IOptions.GetNamedOptions(string name)
 {
  return this;
 }
}

第三部,定义委托调用时使用的缓存上下文类CacheContext,具体代码如下:

using Microsoft.Framework.Cache.Distributed;
using System;
using System.IO;

namespace Microsoft.Framework.Caching.Redis
{
 internal class CacheContext : ICacheContext
 {
  private readonly MemoryStream _data = new MemoryStream();

  internal CacheContext(string key)
  {
   Key = key;
   CreatiOnTime= DateTimeOffset.UtcNow;
  }

  /// 
  /// The key identifying this entry.
  /// 
  public string Key { get; internal set; }

  /// 
  /// The state passed into Set. This can be used to avoid closures.
  /// 
  public object State { get; internal set; }

  public Stream Data { get { return _data; } }

  internal DateTimeOffset CreationTime { get; set; } // 可以让委托设置创建时间

  internal DateTimeOffset&#63; AbsoluteExpiration { get; private set; }

  internal TimeSpan&#63; SlidingExpiration { get; private set; }

  public void SetAbsoluteExpiration(TimeSpan relative) // 可以让委托设置相对过期时间
  {
   if (relative <= TimeSpan.Zero)
   {
    throw new ArgumentOutOfRangeException("relative", relative, "The relative expiration value must be positive.");
   }
   AbsoluteExpiration = CreationTime + relative;
  }

  public void SetAbsoluteExpiration(DateTimeOffset absolute) // 可以让委托设置绝对过期时间
  {
   if (absolute <= CreationTime)
   {
    throw new ArgumentOutOfRangeException("absolute", absolute, "The absolute expiration value must be in the future.");
   }
   AbsoluteExpiration = absolute.ToUniversalTime();
  }

  public void SetSlidingExpiration(TimeSpan offset) // 可以让委托设置offset过期时间
  {
   if (offset <= TimeSpan.Zero)
   {
    throw new ArgumentOutOfRangeException("offset", offset, "The sliding expiration value must be positive.");
   }
   SlidingExpiration = offset;
  }

  internal long&#63; GetExpirationInSeconds()
  {
   if (AbsoluteExpiration.HasValue && SlidingExpiration.HasValue)
   {
    return (long)Math.Min((AbsoluteExpiration.Value - CreationTime).TotalSeconds, SlidingExpiration.Value.TotalSeconds);
   }
   else if (AbsoluteExpiration.HasValue)
   {
    return (long)(AbsoluteExpiration.Value - CreationTime).TotalSeconds;
   }
   else if (SlidingExpiration.HasValue)
   {
    return (long)SlidingExpiration.Value.TotalSeconds;
   }
   return null;
  }

  internal byte[] GetBytes()
  {
   return _data.ToArray();
  }
 }
}

最后一步定义,RedisCache中需要的根据key键获取缓存值的快捷方法,代码如下:

using StackExchange.Redis;
using System;

namespace Microsoft.Framework.Caching.Redis
{
 internal static class RedisExtensions
 {
  private const string HmGetScript = (@"return redis.call('HMGET', KEYS[1], unpack(ARGV))");

  internal static RedisValue[] HashMemberGet(this IDatabase cache, string key, params string[] members)
  {
   var redisMembers = new RedisValue[members.Length];
   for (int i = 0; i 

至此,所有的工作就完成了,将该缓存实现注册为Session的provider的代码方法如下:

app.UseDistributedSession(new RedisCache(new RedisCacheOptions()
{
 COnfiguration= "此处填写 redis的地址",
 InstanceName = "此处填写自定义实例名"
}), optiOns=>
{
 options.COOKIEHttpOnly= true;
});

参考:http://www.mikesdotnetting.com/article/270/sessions-in-asp-net-5

关于Caching

默认情况下,本地缓存使用的是IMemoryCache接口的示例,可以通过获取该接口的示例来对本地缓存进行操作,示例代码如下:

var cache = app.ApplicationServices.GetRequiredService();
var obj1 = cache.Get("key1");
bool obj2 = cache.Get("key2");

对于,分布式缓存,由于AddCaching,默认将IMemoryCache实例作为分布式缓存的provider了,代码如下:

public static class CachingServicesExtensions
{
 public static IServiceCollection AddCaching(this IServiceCollection collection)
 {
  collection.AddOptions();
  return collection.AddTransient()
   .AddSingleton();
 }
}

所以,要使用新的分布式Caching实现,我们需要注册自己的实现,代码如下:

services.AddTransient();
services.Configure(opt =>
{
 opt.COnfiguration= "此处填写 redis的地址";
 opt.InstanceName = "此处填写自定义实例名";
});

基本的使用方法如下:

var cache = app.ApplicationServices.GetRequiredService();
cache.Connect();
var obj1 = cache.Get("key1"); //该对象是流,需要将其转换为强类型,或自己再编写扩展方法
var bytes = obj1.ReadAllBytes();

推荐阅读
  • 单点登录原理及实现方案详解
    本文详细介绍了单点登录的原理及实现方案,其中包括共享Session的方式,以及基于Redis的Session共享方案。同时,还分享了作者在应用环境中所遇到的问题和经验,希望对读者有所帮助。 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • t-io 2.0.0发布-法网天眼第一版的回顾和更新说明
    本文回顾了t-io 1.x版本的工程结构和性能数据,并介绍了t-io在码云上的成绩和用户反馈。同时,还提到了@openSeLi同学发布的t-io 30W长连接并发压力测试报告。最后,详细介绍了t-io 2.0.0版本的更新内容,包括更简洁的使用方式和内置的httpsession功能。 ... [详细]
  • 本文介绍了Hyperledger Fabric外部链码构建与运行的相关知识,包括在Hyperledger Fabric 2.0版本之前链码构建和运行的困难性,外部构建模式的实现原理以及外部构建和运行API的使用方法。通过本文的介绍,读者可以了解到如何利用外部构建和运行的方式来实现链码的构建和运行,并且不再受限于特定的语言和部署环境。 ... [详细]
  • Oracle优化新常态的五大禁止及其性能隐患
    本文介绍了Oracle优化新常态中的五大禁止措施,包括禁止外键、禁止视图、禁止触发器、禁止存储过程和禁止JOB,并分析了这些禁止措施可能带来的性能隐患。文章还讨论了这些禁止措施在C/S架构和B/S架构中的不同应用情况,并提出了解决方案。 ... [详细]
  • SpringMVC工作流程概述
    SpringMVC工作流程概述 ... [详细]
  • 云原生应用最佳开发实践之十二原则(12factor)
    目录简介一、基准代码二、依赖三、配置四、后端配置五、构建、发布、运行六、进程七、端口绑定八、并发九、易处理十、开发与线上环境等价十一、日志十二、进程管理当 ... [详细]
  • 基于分布式锁的防止重复请求解决方案
    一、前言关于重复请求,指的是我们服务端接收到很短的时间内的多个相同内容的重复请求。而这样的重复请求如果是幂等的(每次请求的结果都相同,如查 ... [详细]
  • [翻译]微服务设计模式5. 服务发现服务端服务发现
    服务之间需要互相调用,在单体架构中,服务之间的互相调用直接通过编程语言层面的方法调用就搞定了。在传统的分布式应用的部署中,服务地 ... [详细]
  • 玩转直播系列之消息模块演进(3)
    一、背景即时消息(IM)系统是直播系统重要的组成部分,一个稳定的,有容错的,灵活的,支持高并发的消息模块是影响直播系统用户体验的重要因素。IM长连接服务在直播系统有发挥着举足轻重的 ... [详细]
  • 本文介绍了Web学习历程记录中关于Tomcat的基本概念和配置。首先解释了Web静态Web资源和动态Web资源的概念,以及C/S架构和B/S架构的区别。然后介绍了常见的Web服务器,包括Weblogic、WebSphere和Tomcat。接着详细讲解了Tomcat的虚拟主机、web应用和虚拟路径映射的概念和配置过程。最后简要介绍了http协议的作用。本文内容详实,适合初学者了解Tomcat的基础知识。 ... [详细]
  • 像跟踪分布式服务调用那样跟踪Go函数调用链 | Gopher Daily (2020.12.07) ʕ◔ϖ◔ʔ
    每日一谚:“Acacheisjustamemoryleakyouhaven’tmetyet.”—Mr.RogersGo技术专栏“改善Go语⾔编程质量的50个有效实践” ... [详细]
  • 14亿人的大项目,腾讯云数据库拿下!
    全国人 ... [详细]
  • Asp.Net MVC 测试应用程序
    建立一个Asp.NetMVC项目的时候,如果选择建立测试项目,那么系统会为我们建立一个项目所对应的测试项目。包含了Controller文件夹中对应的Controller单元测试文件, ... [详细]
author-avatar
mobiledu2502902523
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有