解讀ASP.NET 5 & MVC6系列(8):Session與Caching

在以前的版本中,Session存在於System.Web中,新版ASP.NET 5中因爲不在依賴於System.Web.dll庫了,因此相應的,Session也就成了ASP.NET 5中一個可配置的模塊(middleware)了。html

配置啓用Session

ASP.NET 5中的Session模塊存在於Microsoft.AspNet.Session類庫中,要啓用Session,首先須要在project.json中的dependencies節點中添加以下內容:redis

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

而後在ConfigureServices中添加Session的引用(並進行配置):json

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<SessionOptions>委託則可讓你修改默認選項,好比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類型,代碼以下:cookie

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的設置和獲取了: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數據進行設置和獲取的代碼,示例以下:app

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<SessionOptions> 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<ICacheContext> 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<RedisCacheOptions> 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<ICacheContext> 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 ? 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<RedisCacheOptions>
{
    public string Configuration { get; set; }

    public string InstanceName { get; set; }

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

    RedisCacheOptions IOptions<RedisCacheOptions>.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;
        }

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

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

        public Stream Data { get { return _data; } }

        internal DateTimeOffset CreationTime { get; set; } // 可讓委託設置建立時間

        internal DateTimeOffset? AbsoluteExpiration { get; private set; }

        internal TimeSpan? 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? 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 < members.Length; i++)
            {
                redisMembers[i] = (RedisValue)members[i];
            }
            var result = cache.ScriptEvaluate(HmGetScript, new RedisKey[] { key }, redisMembers);
            // TODO: Error checking?
            return (RedisValue[])result;
        }
    }
}

至此,全部的工做就完成了,將該緩存實現註冊爲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<IMemoryCache>();
var obj1 = cache.Get("key1");
bool obj2 = cache.Get<bool>("key2");

對於,分佈式緩存,因爲AddCaching,默認將IMemoryCache實例做爲分佈式緩存的provider了,代碼以下:

public static class CachingServicesExtensions
{
    public static IServiceCollection AddCaching(this IServiceCollection collection)
    {
        collection.AddOptions();
        return collection.AddTransient<IDistributedCache, LocalCache>()
            .AddSingleton<IMemoryCache, MemoryCache>();
    }
}

因此,要使用新的分佈式Caching實現,咱們須要註冊本身的實現,代碼以下:

services.AddTransient<IDistributedCache, RedisCache>();
services.Configure<RedisCacheOptions>(opt =>
{
    opt.Configuration = "此處填寫 redis的地址";
    opt.InstanceName = "此處填寫自定義實例名";
});

基本的使用方法以下:

var cache = app.ApplicationServices.GetRequiredService<IDistributedCache>();
cache.Connect();
var obj1 = cache.Get("key1"); //該對象是流,須要將其轉換爲強類型,或本身再編寫擴展方法
var bytes = obj1.ReadAllBytes();

同步與推薦

本文已同步至目錄索引:解讀ASP.NET 5 & MVC6系列

相關文章
相關標籤/搜索