[转] .net core Session , Working with a distributed cache
2017-02-04 11:24
549 查看
本文转自: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+
Cached data is coherent on all web servers. Users don't see different results depending on which web server handles their request
Cached data survives web server restarts and deployments. Individual web servers can be removed or added without impacting the cache.
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
Get, GetAsync+
Takes a string key and retrieves a cached item as a
Set, SetAsync+
Adds an item (as
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
Specify the dependencies needed in project.json.
Configure the specific implementation of
From the app's `Middleware or MVC controller classes, request an instance of
+
Note
There is no need to use a Singleton or Scoped lifetime for
The following example shows how to use an instance of
Copy
C#
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
The following code from Startup.cs shows the value being set:+
Copy
C#
Note
Since
You configure the Redis implementation in
In the sample code, a
Copy
C#
Note
To install Redis on your local machine, install the chocolatey package http://chocolatey.org/packages/redis-64/ and run
To use sql-cache tool add SqlConfig.Tools to the tools section of the project.json file and run dotnet restore.+
Copy
C#
Test SqlConfig.Tools by running the following command+
Copy
none
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
The created table have the following schema:+
+
Like all cache implementations, your app should get and set cache values using an instance of
Copy
C#
Note
The
Additional resources:+
In memory caching
Redis Cache on Azure
SQL Database on Azure
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:+Cached data is coherent on all web servers. Users don't see different results depending on which web server handles their request
Cached data survives web server restarts and deployments. Individual web servers can be removed or added without impacting the cache.
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
IDistributedCacheinterface.+
The IDistributedCache Interface
TheIDistributedCacheinterface includes synchronous and asynchronous methods. The interface allows items to be added, retrieved, and removed from the distributed cache implementation. The
IDistributedCacheinterface 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
IDistributedCacheinterface:+
Specify the dependencies needed in project.json.
Configure the specific implementation of
IDistributedCachein your
Startupclass's
ConfigureServicesmethod, and add it to the container there.
From the app's `Middleware or MVC controller classes, request an instance of
IDistributedCachefrom the constructor. The instance will be provided by Dependency Injection (DI).
+
Note
There is no need to use a Singleton or Scoped lifetime for
IDistributedCacheinstances (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
IDistributedCachein a simple middleware component:+
Copy
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Caching.Distributed; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DistCacheSample { public class StartTimeHeader { private readonly RequestDelegate _next; private readonly IDistributedCache _cache; public StartTimeHeader(RequestDelegate next, IDistributedCache cache) { _next = next; _cache = cache; } public async Task Invoke(HttpContext httpContext) { string startTimeString = "Not found."; var value = await _cache.GetAsync("lastServerStartTime"); if (value != null) { startTimeString = Encoding.UTF8.GetString(value); } httpContext.Response.Headers.Append("Last-Server-Start-Time", startTimeString); await _next.Invoke(httpContext); } } // Extension method used to add the middleware to the HTTP request pipeline. public static class StartTimeHeaderExtensions { public static IApplicationBuilder UseStartTimeHeader(this IApplicationBuilder builder) { return builder.UseMiddleware<StartTimeHeader>(); } } }
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
Getand
Setmethods 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#
public void Configure(IApplicationBuilder app, IDistributedCache cache) { var serverStartTimeString = DateTime.Now.ToString(); byte[] val = Encoding.UTF8.GetBytes(serverStartTimeString); cache.Set("lastServerStartTime", val); app.UseStartTimeHeader();
Note
Since
IDistributedCacheis configured in the
ConfigureServicesmethod, it is available to the
Configuremethod 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 aRedisDistributedCacheinstance.+
You configure the Redis implementation in
ConfigureServicesand access it in your app code by requesting an instance of
IDistributedCache(see the code above).+
In the sample code, a
RedisCacheimplementation is used when the server is configured for a
Stagingenvironment. Thus the
ConfigureStagingServicesmethod configures the
RedisCache:+
Copy
C#
/// <summary> /// Use Redis Cache in Staging /// </summary> /// <param name="services"></param> public void ConfigureStagingServices(IServiceCollection services) { services.AddDistributedRedisCache(options => { options.Configuration = "localhost"; options.InstanceName = "SampleInstance"; }); }
Note
To install Redis on your local machine, install the chocolatey package http://chocolatey.org/packages/redis-64/ and run
redis-serverfrom 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#
"tools": { "Microsoft.AspNetCore.Server.IISIntegration.Tools": { "version": "1.0.0-preview2-final", "imports": "portable-net45+win8+dnxcore50" }, "Microsoft.Extensions.Caching.SqlConfig.Tools": "1.0.0-preview2-final" },
Test SqlConfig.Tools by running the following command+
Copy
none
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
C:\DistCacheSample\src\DistCacheSample>dotnet sql-cache create "Data Source=(localdb)\v11.0;Initial Catalog=DistCache;Integrated Security=True;" dbo TestCache info: Microsoft.Extensions.Caching.SqlConfig.Tools.Program[0] 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
SqlServerCachein the
Productionenvironment (so it is configured in
ConfigureProductionServices).+
Copy
C#
/// Use SQL Server Cache in Production /// </summary> /// <param name="services"></param> public void ConfigureProductionServices(IServiceCollection services) { services.AddDistributedSqlServerCache(options => { options.ConnectionString = @"Data Source=(localdb)\v11.0;Initial Catalog=DistCache;Integrated Security=True;"; options.SchemaName = "dbo"; options.TableName = "TestCache"; }); }
Note
The
ConnectionString(and optionally,
SchemaNameand
TableName) should typically be stored outside of source control (such as UserSecrets), as they may contain credentials.+
Recommendations
When deciding which implementation ofIDistributedCacheis 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:+
In memory caching
Redis Cache on Azure
SQL Database on Azure
相关文章推荐
- Working with Multiple Forms in Visual Basic .NET: Upgrading to .NET
- Working with Web Resources in ASP.NET 2.0
- [转载] Asp.net中Application Session Cookie ViewState Cache Hidden
- Asp.net中Application Session Cookie ViewState Cache Hidden 区别
- Asp.net中Application Session Cookie ViewState Cache Hidden
- Working with regular expressions in .NET
- Mobile IE6 Standard ASP.NET - onblur not working for , problems with getAttribute
- [本周]随手记下 Asp.net中Application Session Cookie ViewState Cache Hidden
- [本周]随手记下 Asp.net中Application Session Cookie ViewState Cache Hidden
- Working with ADO.NET Schema APIs
- Chapter 7. Working with ASP.NET and VB .NET
- Working with Data in ASP.NET 2.0 :: Using TemplateFields in the GridView Control
- Working with Data in ASP.NET 2.0 :: Master Pages and Site Navigation
- 2006年11月9日 Working with Data and ASP.NET 2.0
- ASP.Net中的缓存方案(不仅仅是Cache和Session)(转)
- ASP.NET SQLCacheDependency with SQLite and Triggers
- Unrecognized Attribute 'xmlns' when working with VS.NET Express Edition
- Working with Windows Workflow Foundation in ASP.NET
- Asp.net中Application Session Cookie ViewState Cache Hidden
- Enterprise Services with the .NET Framework: Developing Distributed Business Solutions with .NET Ent