The first sentence of the text – “this article has participated in the good article calling order activities, click to see: back end, big front end of the double track submission, 20,000 yuan prize pool for you to challenge!”

About me

The author blog | start

Caching Basics

Caching can significantly improve application performance and scalability by reducing the amount of work required to generate content. Caching is best for data that changes infrequently and is expensive to generate. With caching, you can make a much faster copy of the data returned from the data source. Applications should be written and tested so that they never rely on cached data.

ASP.NET Core supports several different caches. The simplest cache is based on IMemoryCache. IMemoryCache represents the cache stored in the memory of the Web server. Applications running on server farms (multiple servers) should ensure that the session is stuck when using the in-memory cache. A sticky session ensures that subsequent requests from the client are sent to the same server.

An in-memory cache can store any object. The distributed cache interface is limited to byte[]. The in-memory and distributed caches treat cached items as key-value pairs.

Cache guide

  • Code should always have a fallback option to get the data, rather than relying on available cache values.

  • The cache uses a rare resource memory, limiting cache growth:

    • Do not use external input as the cache key.
    • Use expiration to limit cache growth.
    • Use SetSize, Size, and SizeLimit to limit the cache Size]. The ASP.NET Core runtime does not limit the cache size based on memory pressure. Developers need to limit the cache size.

use

DI injection

Create a NetCore console project to demonstrate the caching project.

The console project has only one initialized program.cs file. To code a project based on NetCore, each step is to create a base template, using dependency injection.

nuget install Microsoft.Extensions.Hosting
Copy the code
public static class Program { static async void Main(string[] args) { var builder = new HostBuilder().ConfigureServices((context, service) => { }); await builder.RunConsoleAsync(); }}Copy the code

Into the cache service, console library need to download the Microsoft Extensions. Caching. The Memory

nuget install Microsoft.Extensions.Caching.Memory
Copy the code
public static class Program { static async void Main(string[] args) { var builder = new HostBuilder().ConfigureServices((context, service) => { service.AddMemoryCache(); service.AddScoped<CacheService>(); AddHostedService<BackgroundJob>(); // Background execution method}); await builder.RunConsoleAsync(); }}Copy the code

Background services

public class BackgroundJob : IHostedService { private readonly CacheService _cacheService; public BackgroundJob(CacheService cacheService) { _cacheService = cacheService; } public Task StartAsync(CancellationToken cancellationToken) { _cacheService.Action(); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; }}Copy the code

Summary of MemoryCache usage

IMemoryCache is automatically injected through the constructor

public class CacheService { private readonly IMemoryCache _memoryCache; public CacheService(IMemoryCache memoryCache) { _memoryCache = memoryCache; }}Copy the code

The most basic use

The Set method sets the cache based on the Key. By default, the cache does not expire

The Get method retrieves the cache based on the Key

Public void BaseCache() {string cacheKey = "timestamp"; //set cache _memoryCache.Set(cacheKey, DateTime.Now.ToString()); //get cache Console.WriteLine(_memoryCache.Get(cacheKey)); }Copy the code

IMemoryCache provides some good syntax candy for developers to use. See the document below for details

Public void ActionUse() {// scene - if the cache is present, take it out. String cacheKey = "timestamp"; string cacheKey = "timestamp"; if (_memoryCache.Get(cacheKey) ! = null) { _memoryCache.Set(cacheKey, DateTime.Now.ToString()); } else { Console.WriteLine(_memoryCache.Get(cacheKey)); } var dataCacheValue = _memoryCache.getorCreate (cacheKey, entry => {return datetime.now.tostring (); }); Console.WriteLine(dataCacheValue); // Delete the cache _memoryCache.remove (cacheKey); _memoryCache.trygetValue (cacheKey, out string cacheValue); Console.WriteLine(cacheValue); }Copy the code

Cache expiration Policy

There are two common ways to set the cache

  1. Absolute expiration (specifies to expire at a fixed point in time)
  2. Slide expiration (expire if not hit within a period of time)
  3. Combination expiration (absolute expiration + sliding expiration)

Absolute maturity

The expiration policy will expire in five seconds

//set absolute cache
string cacheKey = "absoluteKey";
_memoryCache.Set(cacheKey, DateTime.Now.ToString(), TimeSpan.FromSeconds(5));
​
//get absolute cache
for (int i = 0; i < 6; i++)
{
    Console.WriteLine(_memoryCache.Get(cacheKey));
    Thread.Sleep(1000);
}
Copy the code

Sliding due

Expiration policy The sliding expiration time is 2 seconds. If the access is within 2 seconds, the expiration time is later. If there is no access within a 2-second interval, the cache expires

//set slibing cache
string cacheSlibingKey = "slibingKey";
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
options.SlidingExpiration = TimeSpan.FromSeconds(2);
​
_memoryCache.Set(cacheSlibingKey, DateTime.Now.ToString(), options);
​
//get slibing cache
for (int i = 0; i < 2; i++)
{
    Console.WriteLine(_memoryCache.Get(cacheSlibingKey));
    Thread.Sleep(1000);
}
for (int i = 0; i < 2; i++)
{
    Thread.Sleep(2000);
    Console.WriteLine(_memoryCache.Get(cacheSlibingKey));
}
Copy the code

Combination of overdue

Expiry policies

6 seconds absolute expiration +2 seconds slide expiration

Satisfying either cache will invalidate

string cacheCombineKey = "combineKey";
MemoryCacheEntryOptions combineOptions = new MemoryCacheEntryOptions();
combineOptions.SlidingExpiration = TimeSpan.FromSeconds(2);
combineOptions.AbsoluteExpiration = DateTime.Now.AddSeconds(6);
​
_memoryCache.Set(cacheCombineKey, DateTime.Now.ToString(), combineOptions);
​
//get slibing cache
for (int i = 0; i < 2; i++)
{
    Console.WriteLine(_memoryCache.Get(cacheCombineKey));
    Thread.Sleep(1000);
}
​
for (int i = 0; i < 6; i++)
{
    Thread.Sleep(2000);
    Console.WriteLine(i+"|" + _memoryCache.Get(cacheCombineKey));
}
​
Console.WriteLine("------------combineKey End----------------");
Copy the code

Cache status change event

When the cache is updated or deleted, a callback event is triggered to record what the cache has changed.

/// <summary> public void CacheStateCallback() {MemoryCacheEntryOptions Options = new MemoryCacheEntryOptions(); options.AbsoluteExpiration = DateTime.Now.AddSeconds(3 ); options.RegisterPostEvictionCallback(MyCallback, this); //show callback console string cacheKey = "absoluteKey"; _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options); Thread.Sleep(500); _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options); _memoryCache.Remove(cacheKey); } private static void MyCallback(object key, object value, EvictionReason reason, object state) { var message = $"Cache entry state change:{key} {value} {reason} {state}"; ((CacheService)state)._memoryCache.Set("callbackMessage", message); Console.WriteLine(message); }Copy the code

Cache dependency Policy

I’m going to set A cache A and I’m going to set A cache B, which depends on cache A and if cache A is invalidated, cache B is invalidated

Public void CacheDependencyPolicy() {string DependentCTS = "DependentCTS"; string cacheKeyParent = "CacheKeys.Parent"; string cacheKeyChild = "CacheKeys.Child"; var cts = new CancellationTokenSource(); _memoryCache.Set(DependentCTS, cts); // Create a cache policy using (var Entry = _memoryCache.createEntry (cacheKeyParent)) {// Entry.Value = "parent" + DateTime.Now; / / the current key corresponding to the callback event entry. RegisterPostEvictionCallback (MyCallback, this); Set(cacheKeyChild, "Child" + datetime. Now, new CancellationChangeToken(ctS.token)); } string ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent); string ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild); string callBackMsg = _memoryCache.Get<string>("callbackMessage"); Console.WriteLine(" first get "); Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg); Parentkey_memorycache. Get<CancellationTokenSource>(DependentCTS).cancel (); Thread.Sleep(1000); ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent); ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild); callBackMsg = _memoryCache.Get<string>("callbackMessage"); Console.WriteLine(" second get "); Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg); }Copy the code

The resources

Cache memory in AspNetCore

NetCore cache. MemoryCache

Asp.Net Core easy to learn – in. Net Core uses caching and configures dependency policies

NET Core series: MemoryCache expiration

www.cnblogs.com/ants/p/8482…

Blog.csdn.net/u010476739/…