ASP.NET Core using Redis implement a distributed cache: Docker, IDistributedCache, StackExchangeRedis

ASP.NET Core using Redis implement a distributed cache: Docker, IDistributedCache, StackExchangeRedis

Premise: a Linux server, Docker has been installed.

A, Docker run Redis

Mirrored pull Redis

docker pull redis

Queries mirror list

docker imgaes

Several methods of running Redis

① running and set Redis port

docker run -p 6379:6379 -d redis:latest redis-server

docker run -p 6379:6379 -d {镜像id} redis-server

③ endurance of

The Docker Redis data in the physical machine to a persistent

docker run -p 6379:6379 -v {物理机路径}:/data  -d redis:latest redis-server --appendonly yes

Download the Windows version of Redis manager

The Windows version of Redis Desktop Manager 64 Wei 2019.1 (Chinese version) Download https://www.7down.com/soft/233274.html

Download the latest version of the official Genuine https://redisdesktop.com/download

Attached Redis tutorial:

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

.NET uses Redis learning address (seemingly outdated version of this tutorial) https://www.cnblogs.com/cang12138/p/8884362.html

Set up Master / Slaver mode Redis cluster https://blog.csdn.net/lupengfei1009/article/details/88323561#_154

Use Redis Desktop Manager is connected Redis

1565870987(1)

Two, ASP.NET Core distributed cache

ASP.NET Core, the database supports the use of multiple cache, ASP.NET Core provides a unified interface for developers to use.

IDistributedCache

ASP.NET Core 中,使用 IDistributedCache 为开发者提供统一的缓存使用接口,而不必关注使用的是何种数据库。

IDistributedCache]接口提供了以下方法操作的分布式的缓存实现中的项:

  • GetAsync –接受字符串键和检索缓存的项作为byte[]数组如果在缓存中找到。
  • SetAsync –中添加项 (作为byte[]数组) 到使用字符串键的缓存。
  • RefreshAsync –刷新缓存基于其密钥,重置其滑动到期超时值 (如果有) 中的项。
  • RemoveAsync –移除缓存项根据其字符串键值。

IDistributedCache 提供的常用方法如下:

方法 说明
Get(String) 获取Key(键)的值
GetAsync(String, CancellationToken) 异步获取键的值
Refresh(String) 刷新缓存
RefreshAsync(String, CancellationToken) Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any).
Remove(String) 移除某个值
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.

Official documents in great detail https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache?view=aspnetcore-2.2

In ASP.NET Core configuration cache

Create a new ASP.NET Core WebApi project

Nuget Manager installation

Microsoft.Extensions.Caching.StackExchangeRedis

ConfigureServices use the service

services.AddDistributedMemoryCache();

Redis server configuration

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

InstanceName is the name of your custom instance, it will start with this name when you create the cache.

This is configured.

Use Cached

Modify the default generated ValuesController.cs.

Inject caching service

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

And set the cache using the cache:

await _cache.GetAsync("{键名}");
_cache.SetAsync("键名", {值}, {设置});

Delete the original method, 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 = "设置缓存成功", 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 = "设置缓存成功", Data = "key=" + key + "    value=" + value });
        }

Adding QueryString can set the cache contents in the URL, if no arguments, then it uses the default value.

Open https: // localhost: 5001 / api / values / set can see the set defaults.

或者访问 https://localhost:5001/api/values/set?setkey=key11111&setvalue=asafesfdsreg

Custom set the cache value.

1565872816(1)

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

You can get the cached value.

Set the cache expiration time

Use DistributedCacheEntryOptions can set the cache expiration

DistributedCacheEntryOptions has three attributes, represents a relative time, absolute time.

Instructions

        [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 = "设置缓存成功", Data = "key=" + key + "    value=" + value });
        }

Cache 20 seconds, 20 seconds later this cache will be cleared.

Guess you like

Origin www.cnblogs.com/whuanle/p/11360468.html