本文转自:https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed

By Steve Smith+

Distributed caches can improve the performance and scalability of ASP.NET Core apps, especially when hosted in a cloud or server farm environment. This article explains how to work with ASP.NET Core's built-in distributed cache abstractions and implementations.+

View or download sample code+

What is a Distributed Cache

A distributed cache is shared by multiple app servers (see Caching Basics). The information in the cache is not stored in the memory of individual web servers, and the cached data is available to all of the app's servers. This provides several advantages:+

    1. Cached data is coherent on all web servers. Users don't see different results depending on which web server handles their request

    2. Cached data survives web server restarts and deployments. Individual web servers can be removed or added without impacting the cache.

    3. The source data store has fewer requests made to it (than with multiple in-memory caches or no cache at all).

+

Note

If using a SQL Server Distributed Cache, some of these advantages are only true if a separate database instance is used for the cache than for the app's source data.+

Like any cache, a distributed cache can dramatically improve an app's responsiveness, since typically data can be retrieved from the cache much faster than from a relational database (or web service).+

Cache configuration is implementation specific. This article describes how to configure both Redis and SQL Server distributed caches. Regardless of which implementation is selected, the app interacts with the cache using a common IDistributedCache interface.+

The IDistributedCache Interface

The IDistributedCache interface includes synchronous and asynchronous methods. The interface allows items to be added, retrieved, and removed from the distributed cache implementation. The IDistributedCache interface includes the following methods:+

Get, GetAsync+

Takes a string key and retrieves a cached item as a byte[] if found in the cache.+

Set, SetAsync+

Adds an item (as byte[]) to the cache using a string key.+

Refresh, RefreshAsync+

Refreshes an item in the cache based on its key, resetting its sliding expiration timeout (if any).+

Remove, RemoveAsync+

Removes a cache entry based on its key.+

To use the IDistributedCache interface:+

    1. Specify the dependencies needed in project.json.

    2. Configure the specific implementation of IDistributedCache in your Startup class's ConfigureServices method, and add it to the container there.

    3. From the app's `Middleware or MVC controller classes, request an instance of IDistributedCache from the constructor. The instance will be provided by Dependency Injection (DI).

+

Note

There is no need to use a Singleton or Scoped lifetime for IDistributedCache instances (at least for the built-in implementations). You can also create an instance wherever you might need one (instead of using Dependency Injection), but this can make your code harder to test, and violates the Explicit Dependencies Principle.+

The following example shows how to use an instance of IDistributedCache in a simple middleware component:+

Copy
C#
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.Caching.Distributed;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace DistCacheSample
  10. {
  11. public class StartTimeHeader
  12. {
  13. private readonly RequestDelegate _next;
  14. private readonly IDistributedCache _cache;
  15. public StartTimeHeader(RequestDelegate next,
  16. IDistributedCache cache)
  17. {
  18. _next = next;
  19. _cache = cache;
  20. }
  21. public async Task Invoke(HttpContext httpContext)
  22. {
  23. string startTimeString = "Not found.";
  24. var value = await _cache.GetAsync("lastServerStartTime");
  25. if (value != null)
  26. {
  27. startTimeString = Encoding.UTF8.GetString(value);
  28. }
  29. httpContext.Response.Headers.Append("Last-Server-Start-Time", startTimeString);
  30. await _next.Invoke(httpContext);
  31. }
  32. }
  33. // Extension method used to add the middleware to the HTTP request pipeline.
  34. public static class StartTimeHeaderExtensions
  35. {
  36. public static IApplicationBuilder UseStartTimeHeader(this IApplicationBuilder builder)
  37. {
  38. return builder.UseMiddleware<StartTimeHeader>();
  39. }
  40. }
  41. }

In the code above, the cached value is read, but never written. In this sample, the value is only set when a server starts up, and doesn't change. In a multi-server scenario, the most recent server to start will overwrite any previous values that were set by other servers. The Get and Set methods use the byte[] type. Therefore, the string value must be converted using Encoding.UTF8.GetString (for Get) and Encoding.UTF8.GetBytes (for Set).+

The following code from Startup.cs shows the value being set:+

Copy
C#
  1. public void Configure(IApplicationBuilder app,
  2. IDistributedCache cache)
  3. {
  4. var serverStartTimeString = DateTime.Now.ToString();
  5. byte[] val = Encoding.UTF8.GetBytes(serverStartTimeString);
  6. cache.Set("lastServerStartTime", val);
  7. app.UseStartTimeHeader();
Note

Since IDistributedCache is configured in the ConfigureServices method, it is available to the Configure method as a parameter. Adding it as a parameter will allow the configured instance to be provided through DI.+

Using a Redis Distributed Cache

Redis is an open source in-memory data store, which is often used as a distributed cache. You can use it locally, and you can configure an Azure Redis Cache for your Azure-hosted ASP.NET Core apps. Your ASP.NET Core app configures the cache implementation using a RedisDistributedCache instance.+

You configure the Redis implementation in ConfigureServices and access it in your app code by requesting an instance of IDistributedCache (see the code above).+

In the sample code, a RedisCache implementation is used when the server is configured for a Staging environment. Thus the ConfigureStagingServices method configures the RedisCache:+

Copy
C#
  1. /// <summary>
  2. /// Use Redis Cache in Staging
  3. /// </summary>
  4. /// <param name="services"></param>
  5. public void ConfigureStagingServices(IServiceCollection services)
  6. {
  7. services.AddDistributedRedisCache(options =>
  8. {
  9. options.Configuration = "localhost";
  10. options.InstanceName = "SampleInstance";
  11. });
  12. }
Note

To install Redis on your local machine, install the chocolatey package http://chocolatey.org/packages/redis-64/and run redis-server from a command prompt.+

Using a SQL Server Distributed Cache

The SqlServerCache implementation allows the distributed cache to use a SQL Server database as its backing store. To create SQL Server table you can use sql-cache tool, the tool creates a table with the name and schema you specify.+

To use sql-cache tool add SqlConfig.Tools to the tools section of the project.json file and run dotnet restore.+

Copy
C#
  1. "tools": {
  2. "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
  3. "version": "1.0.0-preview2-final",
  4. "imports": "portable-net45+win8+dnxcore50"
  5. },
  6. "Microsoft.Extensions.Caching.SqlConfig.Tools": "1.0.0-preview2-final"
  7. },

Test SqlConfig.Tools by running the following command+

Copy
none
  1. C:\DistCacheSample\src\DistCacheSample>dotnet sql-cache create --help

sql-cache tool  will display usage, options and command help, now you can create tables into sql server, running "sql-cache create" command :+

Copy
none
  1. C:\DistCacheSample\src\DistCacheSample>dotnet sql-cache create "Data Source=(localdb)\v11.0;Initial Catalog=DistCache;Integrated Security=True;" dbo TestCache
  2. info: Microsoft.Extensions.Caching.SqlConfig.Tools.Program[0]
  3. Table and index were created successfully.

The created table have the following schema:+

+

Like all cache implementations, your app should get and set cache values using an instance of IDistributedCache, not a SqlServerCache. The sample implements SqlServerCache in the Production environment (so it is configured in ConfigureProductionServices).+

Copy
C#
  1. /// Use SQL Server Cache in Production
  2. /// </summary>
  3. /// <param name="services"></param>
  4. public void ConfigureProductionServices(IServiceCollection services)
  5. {
  6. services.AddDistributedSqlServerCache(options =>
  7. {
  8. options.ConnectionString = @"Data Source=(localdb)\v11.0;Initial Catalog=DistCache;Integrated Security=True;";
  9. options.SchemaName = "dbo";
  10. options.TableName = "TestCache";
  11. });
  12. }
Note

The ConnectionString (and optionally, SchemaName and TableName) should typically be stored outside of source control (such as UserSecrets), as they may contain credentials.+

Recommendations

When deciding which implementation of IDistributedCache is right for your app, choose between Redis and SQL Server based on your existing infrastructure and environment, your performance requirements, and your team's experience. If your team is more comfortable working with Redis, it's an excellent choice. If your team prefers SQL Server, you can be confident in that implementation as well. Note that A traditional caching solution stores data in-memory which allows for fast retrieval of data. You should store commonly used data in a cache and store the entire data in a backend persistent store such as SQL Server or Azure Storage. Redis Cache is a caching solution which gives you high throughput and low latency as compared to SQL Cache.+

Additional resources:+

[转] .net core Session , Working with a distributed cache的更多相关文章

  1. net core体系-web应用程序-4net core2.0大白话带你入门-10asp.net core session的使用

    asp.net core session的使用   Session介绍 本文假设读者已经了解Session的概念和作用,并且在传统的.net framework平台上使用过. Asp.net core ...

  2. IT咨询顾问:一次吐血的项目救火 java或判断优化小技巧 asp.net core Session的测试使用心得 【.NET架构】BIM软件架构02:Web管控平台后台架构 NetCore入门篇:(十一)NetCore项目读取配置文件appsettings.json 使用LINQ生成Where的SQL语句 js_jquery_创建cookie有效期问题_时区问题

    IT咨询顾问:一次吐血的项目救火   年后的一个合作公司上线了一个子业务系统,对接公司内部的单点系统.我收到该公司的技术咨询:项目启动后没有规律的突然无法登录了,重新启动后,登录一断时间后又无法重新登 ...

  3. .net core session部分浏览器或移动客户端不可用

    .net core session使用有很多文章,这里不再赘述. 问题现象为大部分浏览器或者移动客户端(例如微信.支付宝.钉钉)等都可以正常使用.但部分支付宝用户及钉钉用户确无法使用. 写入后读取不到 ...

  4. asp.net core 系列之Reponse caching之cache in-memory (2)

    这篇文章(主要翻译于官网,水平有限,见谅)讲解asp.net core 中的 Cache in-memory (内存缓存). Cache in-memory in ASP.NET Core Cachi ...

  5. Distributed Cache Coherence at Scalable Requestor Filter Pipes that Accumulate Invalidation Acknowledgements from other Requestor Filter Pipes Using Ordering Messages from Central Snoop Tag

    A multi-processor, multi-cache system has filter pipes that store entries for request messages sent ...

  6. [hadoop](2) MapReducer:Distributed Cache

    前言 本章主要内容是讲述hadoop的分布式缓存的使用,通过分布式缓存可以将一些需要共享的数据在各个集群中共享. 准备工作 数据集:ufo-60000条记录,这个数据集有一系列包含下列字段的UFO目击 ...

  7. asp.net core session丢失问题排查

    最近公司采用asp.net core的站点在外测环境中,总是发现存在session丢失的情况.排查了好久,客户端.AspNetCore.Session的cookie未丢失,session的分布式缓存采 ...

  8. .NET Core Session的简单使用

    前言 在之前的.NET 里,我们可以很容易的使用Session读取值.那今天我们来看看 如何在.NET Core中读取Session值呢? Session 使用Session之前,我们需要到Start ...

  9. .NET Core Session的使用方法

    刚使用.NET Core会不习惯,比如如何使用Session:不仅需要引用相应的类库,还需要在Startup.cs里进行注册. 1.在你的项目上基于NuGet添加: install-package M ...

随机推荐

  1. SiriShortCut模型建立及数据交互逻辑

    1.模型数据需求 意图: 手机号 密码 网关ID 打开该情景的命令 情景号 情景名 情景背景图 添加该意图时的 token值 主程序登陆共享数据 手机号 token值 2.操作逻辑 1.意图被唤起 获 ...

  2. 【转】在Win10家庭版中启用组策略

    源地址:https://www.baidu.com/link?url=tZrD7LVxQEKQUTWUum86LoxyaxWNLs5BeBE2K36TliRi8sjGraKc-iP3TEm6sc_KX ...

  3. win10 + Lubuntu 双系统安装

    win10 + Lubuntu 双系统安装 最近重装了系统,索性直接安装win10 + Lubuntu 双系统,便于在物理机下进行 Linux开发. 这里我选择的 Linux 发行版是 Lubuntu ...

  4. ceph_osd故障检测

    1.     当前monitor可以通过3种途径检测到osd离线 1)      Osd自主上报 2)      Osd通过投票的方式(满足一下条件之一,mon会将osd标记为down) a)     ...

  5. 1、Numpy基础

    NumPy是什么? NumPy是科学计算的基本包在Python中. 这是一个Python库,它提供了一个多维数组对象, 各种派生的对象(如蒙面数组和矩阵),和一个 快速操作数组的各式各样的例程,包括 ...

  6. os模块与 sys模块

    os模块是与操作系统交互的一个接口 ''' os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作 ...

  7. JAVA通过网站域名URL获取该网站的源码(2018

    import java.io.ByteArrayOutputStream;   import java.io.InputStream;   import java.net.HttpURLConnect ...

  8. UVA - 11825 状压DP

    该题目是EMAXX推荐的练习题,刘汝佳的书也有解说 如果S0属于全集,那S0就可以作为一个分组,那么S分组数可以是best{当前S中S0的补集+1} 对于集合类的题目我觉得有点抽象,希望多做多理解把 ...

  9. BZOJ - 4260 01字典树+前后缀

    题意:给定\(a[1...n]\),求\((a_i⊕a_i+1⊕...⊕a_j)+(a_p⊕a_{p+1}⊕...⊕a_{q})\)的最大值,其中\(1≤i≤j<p≤q≤n\) 前后缀最优解预处 ...

  10. UESTC - 621

    f[n]:sigma(i,n),i<n g[n]:sigmaf[i],i<=n #include<bits/stdc++.h> using namespace std; con ...