Redis implements distributed caching

Redis implements distributed caching

IDistributedCache,StackExchangeRedis

Redis learning tutorial:

Windows installs redis and sets the redis service to start automatically:
https://blog.csdn.net/qq_40732336/article/details/122653953

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

Build a Redis cluster in master / slave mode https://blog.csdn.net/lupengfei1009/article/details/88323561#_154

Connect to Redis using Redis Desktop Manager

2, ASP Net core uses distributed caching

ASP.NET Core supports the use of multiple databases for caching, ASP Net core provides a unified interface for developers.

IDistributedCache

ASP.NET Core, using IDistributedCache provides developers with a unified cache interface without paying attention to the database used.

The IDistributedCache] interface provides items in a distributed cache implementation that operate with the following methods:

  • GetAsync – accepts string keys and retrieves cached items as byte [] arrays if found in the cache.
  • SetAsync – adds an item (as a byte [] array) to the cache using the string key.
  • RefreshAsync – refreshes the cache and resets the entries in its sliding expiration timeout value (if any) based on its key.
  • RemoveAsync – removes cache entries based on their string key values.

The common methods provided by IDistributedCache are as follows:

methodexplain
Get(String)Gets the value of the key
GetAsync(String, CancellationToken)Get the value of the key asynchronously
Refresh(String)Refresh cache
RefreshAsync(String, CancellationToken)Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any).
Remove(String)Remove a 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 documents are very detailed https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache?view=aspnetcore-2.2

ASP. Configure cache in. Net core

Create a new ASP Net core webapi project

Nuget Manager installation

Microsoft.Extensions.Caching.StackExchangeRedis

Services used in ConfigureServices

services.AddDistributedMemoryCache();

Configure Redis server

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

InstanceName is your customized instance name, which will start when creating the cache.

This completes the configuration.

Use cache

Modify the default generated valuescontroller cs.

Injection cache service

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

Set cache and use cache:

await _cache.GetAsync("{Key name}");
_cache.SetAsync("Key name", {value}, {set up});

Delete the original method 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 = "Set cache 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 = "Setting cache succeeded", Data = "key=" + key + "    value=" + value });
        }

Adding QueryString to the URL can set the cache content. If there are no parameters, the default value will be used.

open https://localhost:5001/api/values/set You can see that the default value is set.

Or visit https://localhost:5001/api/values/set?setkey=key11111&setvalue=asafesfdsreg

Custom settings cache values.

open https://localhost:5001/api/values/get?setkey=key11111

You can get the cache value.

Set cache expiration time

Use the DistributedCacheEntryOptions to set the cache expiration time

DistributedCacheEntryOptions has three properties, representing relative time and absolute time.

usage method

        [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 = "Setting cache succeeded", Data = "key=" + key + "    value=" + value });
        }

Cache for 20 seconds, after which the cache will be cleared.

reference resources: https://www.cnblogs.com/whuanle/p/11360468.html

Keywords: Redis Distribution Cache

Added by jamesjohnson88 on Wed, 26 Jan 2022 14:15:33 +0200