.NET Core applications using distributed cache and memory cache

.NET Core for caching provides good support, we can not only select the data in the cache memory in the application process itself can also be distributed in the form of using the cached data is stored in a "central database". For distributed caches, .NET Core provides native support for Redis and SQL Server. In addition to this an independent cache system, ASP.NET Core also achieved by means of a middleware "response caching", it will respond in accordance with the embodiment of the entire cache HTTP caching specification. ASP.NET Core supports a variety of different cache.

Four ways in response to the common cache

1, the memory cache

  As the name suggests, it is cached in memory, along with the default application lifecycle

2, response caching

  Caching reduces the response to the client or agent to the number of requests sent by the web server. Response caching also reduces the work of the web server performs to generate a response. In response cache-control header, which specifies how the client, agency and response caching middleware.

3, in response to the cache middleware

  Microsoft.AspNetCore.ResponseCaching 包中的ResponseCaching

4, distributed cache

  More commonly used is based on a distributed caching and Redis databases.

Here we focus here and distributed cache memory cache.

If you see this text, indicating that you are using an RSS reader or switched from "a tree - blog Park", the original address: https://www.cnblogs.com/atree/p/netcore-Distributed-Cache.html 

The data is cached in memory - memory cache

And calls for this kind of IO operations against the database and remote services, applications for memory access performance will provide more than an order of magnitude improvement, so the cached data directly in the content of the application process naturally has the best performance advantages. And an application programming interface definition associated memory-based cache in NuGet package "Microsoft.Extensions.Caching.Memory", in particular cache implementation MemoryCache service object named in the latter we achieved IMemoryCache interface for all collectively for all types and the corresponding object. Since the cache object is placed directly into memory, the middle does not involve the issue of persistent storage, naturally without regard for the cache object serialization problems, so this mode supports any type of memory cache object.

This object is MemoryCache for nothing more than the operation of the memory cache and data cache fetch, by these two basic operations described above to complete. If we do MemoryCache service registration at startup in a ASP.NET Core application, we can get the service object cache set and get data from anywhere, so for cache programming is very simple. I do not want to look at these, looking directly at the case.

static void Main (string[] args) 
{ MemoryCache memoryCache
= new MemoryCache(new MemoryCacheOptions()); memoryCache.Set("name", "tom"); var value = memoryCache.Get("name"); Console.WriteLine(value); Console.ReadKey(); }

 Set an expiration time:

static void Main (string[] args) 
{ MemoryCache memoryCache
= new MemoryCache (new MemoryCacheOptions ()); memoryCache.Set ("name", "jack", new MemoryCacheEntryOptions () { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds (5) //设置为5秒后过期 }); while (true) { System.Threading.Thread.Sleep (1000); string value; if (!memoryCache.TryGetValue ("name", out value)) { value = "已过期"; } Console.WriteLine (value); } }

The highest performance memory-based cache, but because it is actually cached data exists on the Web services hosted ASP.NET Core applications, for applications deployed in a clustered server cache data inconsistency happens. For this deployment scenario, we need to cache data in one separate storage center, so that all the Web servers share the same copy of the cached data, we will cache this form is called "distributed cache." ASP.NET Core provides distributed cache storage in the form of two types of native, one is based on the Redis NoSQL databases, the other is Microsoft's own relational database SQL Server.

Redis-based distributed cache

Redis NoSQL database number more popular, a lot of programming platform of choice as it will be distributed cache, then we have to demonstrate how how Redis-based distributed cache in a ASP.NET Core applications. Considering some people may not have experienced Redis, so let's briefly explain how to install Redis. Redis easiest installation method is to use Chocolatey (https://chocolatey.org/) command line, which is under the Windows platform, an excellent package management tools (similar to NPM).

Using PowerShell (version requires more V3) command line

IWR https: //chocolatey.org/install.ps1 -UseBasicParsing | IEX

Or ordinary CMD.exe command line:

@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

To install Chocolatey. Ensuring Chocolatey be installed locally normal circumstances, we can execute execute the following command to install or upgrade 64 of Redis.

C:\>choco install redis-64
C:\>choco upgrade redis-64

Start Redis server is also very simple, we only need to perform redis-server command to form the command line. If you see the output shown below after performing the named Redis said local server is normally started, the result output port network monitoring server specifies employed. For administrative purposes, you can download and install: Client Tools: RedisDesktopManager.

Redis for distributed cache implementation in NuGet package "Microsoft.Extensions.Caching.Redis" in, so we need to make sure that the package is properly installed NuGet. Regardless of using Redis, SQL Server or other distributed storage, distributed cache for the operation are achieved in DistributedCache this service object to, the corresponding service interface IDistributedCache.

IDistributedCache interface contains synchronous and asynchronous methods. Interface allows you to add in distributed cache implementation, retrieve and delete items. IDistributedCache interface includes the following methods:

Get、 GetAsync

Using a string key and retrieve the cache entry (if found in the cache) to byte [] form.

Set、SetAsync

Add Item string key byte [] form) to the cache.

Refresh、RefreshAsync

The entries in the cache to refresh, and reset its adjustable timeout value expires (if any).

Remove、RemoveAsync

Delete cache entry based on key.

Register at project start Setup.cs in: Redis service

public  void ConfigureServices (IServiceCollection Services) 
{
// add the distributed cache service Redis service services.AddDistributedRedisCache (Options => { // for configuring the Redis Configuration.GetConnectionString connection ( "RedisConnectionString") read configuration information string = options.Configuration " localhost " ; // Configuration.GetConnectionString ( "RedisConnectionString"); // the Redis instance name RedisDistributedCache options.InstanceName = " RedisDistributedCache " ; }); services.AddMvc (); }

Examples of objects constructed injection

private DistributedCache _Cache;

/// <summary>
///   构造注入
/// </summary>
/// <param name="Cache"></param>
public ValuesController (IDistributedCache Cache) {
    _Cache = new DistributedCache (Cache);
}

DistributedCache call methods in the class

[HttpGet ("{id}")]
public string Get (int id) {
    //添加
    bool booladd = _Cache.Add ("id", "sssss");
    //验证
    bool boolExists = _Cache.Exists ("id");
    //获取
    object obj = _Cache.Get ("id");
    //删除
    bool boolRemove = _Cache.Remove ("id");
    //修改
    bool boolModify = _Cache.Modify ("id", "ssssssss");

    return obj.ToString ();
}

Distributed caching of SQL Server

In addition to using Redis NoSQL databases such mainstream to support distributed caching, distributed cache in the design of Microsoft has not forgotten its own relational database using SQL Server. SQL Server for distributed cache is implemented in "Microsoft.Extensions.Caching.SqlServer" NuGet this package, we come NuGet ensure that the package is properly loaded into the application's presentation.

Called for SQL Server distributed cache, in fact, is to identify the cache data array of bytes stored in SQL Server databases in a data table has a fixed structure, because we have to create such a cache table, the table you can make use of a tool called sql-cache to create. Before you create a cache table to perform sql-cache tools, we need to add the appropriate NuGet package "Microsoft.Extensions.Caching.SqlConfig.Tools" follows the form of the tool in project.json file.

SqlServer database engine created in a database, named: TestDb, open the project root directory, perform the operation to create cache data table after executing the command if the output information: Table and index were created successfully represented cache table created successfully.

dotnet sql-cache create "Server=.\SQLEXPRESS;User=sa;Password=123456;Database=TestDb" dbo AspNetCoreCache

Registered in the distributed cache in Startup.cs

public void ConfigureServices (IServiceCollection services) {
    services.AddDistributedSqlServerCache (options => {
        options.SystemClock = new BLL.LocalSystemClock ();
        options.ConnectionString = this.Configuration["ConnectionString"];
        options.SchemaName = "dbo";
        options.TableName = "AspNetCoreCache";
        options.DefaultSlidingExpiration = TimeSpan.FromMinutes (1);
        options.ExpiredItemsDeletionInterval = TimeSpan.FromMinutes ( 5 ); 
    }); 
    ... 
}

Distributed cache in the controller

[Route ("api/Home")]
[ApiController]
public class HomeController : Controller {
    private IDistributedCache cache;
    public HomeController (IDistributedCache cache) {
        this.cache = cache;
    }

    [HttpGet ("Index")]
    public async Task<ActionResult<string>> SetTime () {
        var CurrentTime = DateTime.Now.ToString ();
        await this.cache.SetStringAsync ("CurrentTime", CurrentTime);
        return CurrentTime;
    }

    [HttpGet ("GetTime")]
    public async Task<ActionResult<string>> GetTime () {
        var CurrentTime = await this.cache.GetStringAsync ("CurrentTime");
        return CurrentTime;
    }
}

In this way, with up very convenient.

Guess you like

Origin www.cnblogs.com/atree/p/netcore-Distributed-Cache.html