用分布式缓存提升ASP.NET Core性能
2018-04-13
得益于纯净、轻量化并且跨平台支持的特性,ASP.NET Core作为热门Web应用开发框架,其高性能传输和负载均衡的支持已广受青睐。实际上,10-20台Web服务器还是轻松驾驭的。有了多服务器负载的支持,使得Web应用层在业务增长时随时采用水平扩展,ASP.NET Core也能够没有什么负担地处理长事务。然而造成性能瓶颈的地方仍然不可忽视,具体来说首当其冲就是数据存储,无法随着应用层的性能提升而提高大规模数据处理能力,这是因为数据层是没有办法简单通过增加服务器得到改善的。

ASP.NET Core应用有两类数据在数据存储成为瓶颈时突显出来:

  1. 数据库

  2. Session会话

解决方案: 分布式缓存


解决这个性能瓶颈,不妨试试NCache,它是一个开源的支持.NET的分布式缓存,它的优势在于完全基于内存,所以你可以在业务增长时组建内存服务器的集群来实现线性扩展,相比于数据库能节省近八成的成本,并且在读写应用数据上得到更快的体验。NCache很适合存储session会话,在多Web服务器负载时也解决了会话保持的需求。

下图是NCache这类常见的分布式缓存的部署架构。

ASP.NET Core应用数据缓存IDistributedCache


在ASP.NET Core之前,旧的ASP.NET程序的缓存对象是独立进程的,也没有多服务器支持的需要。现今ASP.NET Core推出了IDistributedCache统一接口,定义了分布式缓存的基本接口,类似于日志、注入容器的接口一样,可以无缝提供第三方扩展。

IDistributedCache接口使用示例:

IDistributedCache _cache;

...

private byte[] LoadCustomer(string custId) {

    string key = "Customers:CustomerID:" + custId;

    // is the customer in the cache?

    byte[] customer = _cache.Get(key);

 

    if(customer == null) {

       // the cache doesn't have it. so load from DB

       customer = LoadFromDB(key);

       // And, cache it for next time

       _cache.Set(key, customer);

    }

 

    return customer;

}

NCache是IDistributedCache的一种实现,所以在ASP.NET Cor应用中使用NCache不需要特殊的配置。

以下是IDistributedCache接口的定义(注意每个方法都有对应的Async版本的重载)。

namespace Microsoft.Extensions.Caching.Distributed

{

    public interface IDistributedCache

    {

        // Each of these methods also has an “Async” overload

        byte[] Get(string key);

        void Refresh(string key);

        void Remove(string key);

 

        // Specify absolute & sliding expiration thru options

        void Set(string key, byte[] value, DistributedCacheEntryOptions options);

    }

}

接下来在ASP.NET Core的Startup类中配置NCacheIDistributedCache

public class Startup

{

    ...

    public void ConfigureServices(IServiceCollection services)

    {

        ...

        services.AddNCacheDistributedCache();

        ...

    }

    ...

}

如果对缓存需求不高, 使用IDistributedCache保留了更改分布式缓存灵活性。但是要权衡这种放弃高级缓存特性的成本。为什么不考虑一下NCache?NCache API在ASP.NET Core应用内可以直接使用,和旧的ASP.NET Cache API非常相似,它包含了大量零成本新特性,可以获得企业级的分布式缓存收益。记住一点,看在性能提升和扩展能力的份上,早用早享受。没有这些高级特性,那只能可怜地缓存一些简单数据。这份NCache caching features了解更多差别。

ASP.NET Core会话存储到分布式缓存


旧的ASP.NET的会话状态由框架提供,允许第三方组件以插件形式接入。在ASP.NET Core中的会话也是相似的,采用链式插件调用,有两种方式使用NCache作为ASP.NET Core的会话存储:

1.NCache作为ASP.NET Core的IDistributedCache Provider存储配置

如果把NCache作为ASP.NET Core的IDistributedCache provider进行配置,NCache能自动的成为会话的默认存储方式,不用再有多余的操作。但是相比于旧的ASP.NET会话状态,这种方式能使用到的特性有限。

以下是ASP.NET Core默认会话缺失的地方:

  1. ASP.NET Core无会话锁提供。

  2. 自定义对象的byte数组支持:  ASP.NET Core强制你在把自定义对象存储到会话前先转换成byte数组。

2. NCache作为ASP.NET Core的Sessions Provider配置

比起前一个方式,NCache已经实现了ASP.NET Core的Sessions Provider。这种方式拥有更多的特性可以利用。

以下是在Startup类进行配置的示例。

public class Startup

{

    ...

    public void Configure(IApplicationBuilder app,  IHostingEnvironment env)

    {

        ...

        app.UseNCacheSession();

        ...

    } 

    ...

}

你可以在appsettings.json文件中做如下ASP.NET Core会话配置。

{

    ...

    "NCacheSessions": {

        ...

        "CacheName": "demoCache",

        "EnableLogs": "True",

        "RequestTimeout": "90",

        "EnableDetailLogs": "False",

        "ExceptionsEnabled": "True",

        "WriteExceptionsToEventLog": "False"

    }

    ...

}


Configure NCache IDistributedCache Provider了解更多会话存储配置信息。

NCache是比Redis成为ASP.NET Core更好选择的原因


微软提供了IDistributedCache Providers两种可选方案。一个是SQL Server另一个是Redis。NCache比这两种方案更胜一筹表面上看是因为执行更快,更易扩展,当然还有以下原因:

  1. 原生.NET:  NCache是100%原生.NET,更易融入.NET应用技术栈。反观来自Linux背景的Redis和原生.NET毕竟有兼容潜在问题。

  2. 比Redis更快:  NCache确实比Redis要快。NCache客户端缓存的执行能力表现不俗。

  3. 更多特性:  NCache提供了Redis所没有的分布式缓存特性。参见这里:Redis vs NCache 

NCache更多详情:Nache Details  Edition Comparison  Download 

(原文:How to Optimize ASP.NET Core Performance with Distributed Cache?