Implementing Distributed Caching in ASP.NET Core with Redis: Docker, IDistributedCache, StackExchangeRedis

2019年12月15日 3156点热度 1人点赞 0条评论
内容目录

ASP.NET Core Implements Distributed Caching Using Redis: Docker, IDistributedCache, StackExchangeRedis

Prerequisite: A Linux server with Docker installed.

I. Running Redis in Docker

Pull Redis image

docker pull redis

Query image list

docker images

Several methods to run Redis

  1. Run and set Redis port
docker run -p 6379:6379 -d redis:latest redis-server
docker run -p 6379:6379 -d {image_id} redis-server
  1. Persistence

Persist Redis data from Docker to the host machine

docker run -p 6379:6379 -v {host_path}:/data  -d redis:latest redis-server --appendonly yes

Download Windows version of Redis Desktop Manager

Download link for Windows version of Redis Desktop Manager 64-bit 2019.1 (Chinese version): https://www.7down.com/soft/233274.html

Official latest version download link: https://redisdesktop.com/download

Also attached Redis learning tutorials:

Redis Chinese website: https://www.redis.net.cn/

.NET using Redis learning link (this tutorial version seems outdated): https://www.cnblogs.com/cang12138/p/8884362.html

Setting up a Master/Slave mode Redis cluster: https://blog.csdn.net/lupengfei1009/article/details/88323561#_154

Use Redis Desktop Manager to connect to Redis

1565870987(1)

II. ASP.NET Core Using Distributed Caching

In ASP.NET Core, support for caching using various databases is provided, with a unified interface for developers.

IDistributedCache

In ASP.NET Core, IDistributedCache provides a unified caching interface for developers, without having to focus on which database is used.

The IDistributedCache interface provides the following methods to perform operations on cached items in a distributed cache implementation:

  • GetAsync – Accepts a string key and retrieves the cached item as a byte[] array if found in the cache.
  • SetAsync – Adds an item (as a byte[] array) to the cache using a string key.
  • RefreshAsync – Refreshes the cache based on its key, resetting its sliding expiration timeout (if any) for the item.
  • RemoveAsync – Removes a cached item based on its string key.

Common methods provided by IDistributedCache are as follows:

| Method | Description |
| -------------------------------------------------------------- | ------------------------------------------------------------ |
| Get(String) | Retrieves the value for the specified key |
| GetAsync(String, CancellationToken) | Asynchronously retrieves the value for the specified key |
| Refresh(String) | Refreshes the cache |
| RefreshAsync(String, CancellationToken) | Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any). |
| Remove(String) | Removes a specified value |
| RemoveAsync(String, CancellationToken) | Removes the value with the given key |
| Set(String, Byte[], DistributedCacheEntryOptions) | Sets a value with the given key |
| SetAsync(String, Byte[], DistributedCacheEntryOptions, CancellationToken) | Sets the value with the given key |

The official documentation is very detailed: https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache?view=aspnetcore-2.2

Configuring Caching in ASP.NET Core

Create a new ASP.NET Core WebApi project.

Install via Nuget Package Manager

Microsoft.Extensions.Caching.StackExchangeRedis

Use the service in ConfigureServices

services.AddDistributedMemoryCache();

Configure the Redis server

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
    options.InstanceName = "mvc";
});

InstanceName is your custom instance name that will prefix the cache when created.

The configuration is now complete.

Using Caching

Modify the default generated ValuesController.cs.

Inject the caching service

private readonly IDistributedCache _cache;
public ValuesController(IDistributedCache cache)
{
    _cache = cache;
}

Set and use the cache:

await _cache.GetAsync("{key_name}");
_cache.SetAsync("{key_name}", {value}, {options});

Remove the original methods and add the following code:

[HttpGet("Set")]
public async Task<JsonResult> SetCache(string setkey, string setvalue)
{
    string key = "key1";
    if (!string.IsNullOrEmpty(setkey))
        key = setkey;
    string value = DateTime.Now.ToLongTimeString();
    if (!string.IsNullOrEmpty(setvalue))
        value = setvalue;
    await _cache.SetStringAsync(key, value);
    return new JsonResult(new { Code = 200, Message = "Cache set successfully", Data = "key=" + key + "    value=" + value });
}

[HttpGet("Get")]
public async Task<JsonResult> GetCache(string setkey)
{
    string key = "key1";
    if (!string.IsNullOrEmpty(setkey))
        key = setkey;
    var value = await _cache.GetStringAsync(key);
    return new JsonResult(new { Code = 200, Message = "Cache retrieved successfully", Data = "key=" + key + "    value=" + value });
}

Add QueryString to URL to set cache content; if no parameters are provided, the default values will be used.

Open https://localhost:5001/api/values/set to see the default values set.

Alternatively, visit https://localhost:5001/api/values/set?setkey=key11111&setvalue=asafesfdsreg to customize the cached value.

1565872816(1)

Open https://localhost:5001/api/values/get?setkey=key11111 to retrieve the cached value.

Setting Cache Expiration Time

Use DistributedCacheEntryOptions to set cache expiration time.

DistributedCacheEntryOptions has three properties for relative time and absolute time.

Usage

[HttpGet("Set")]
public async Task<JsonResult> SetCache(string setkey, string setvalue)
{
    string key = "key1";
    if (!string.IsNullOrEmpty(setkey))
        key = setkey;
    string value = DateTime.Now.ToLongTimeString();
    if (!string.IsNullOrEmpty(setvalue))
        value = setvalue;

    var options = new DistributedCacheEntryOptions()
    .SetSlidingExpiration(TimeSpan.FromSeconds(20));

    await _cache.SetStringAsync(key, value, options);
    return new JsonResult(new { Code = 200, Message = "Cache set successfully", Data = "key=" + key + "    value=" + value });
}

The cache will expire after 20 seconds; this cache will be cleared after 20 seconds.

痴者工良

高级程序员劝退师

文章评论