Using redis cache in .Net core

Install Redis on Windows and add local self-starting service

Build the redis cache locally in Windows and add it to the service of the local computer to ensure that the service is automatically started every time the computer is turned on.

Step one: Download redis (mine is win10, 64-bit)
https://github.com/MicrosoftArchive/redis/releases

Insert image description here

Step 2: Unzip the package and copy the folder to the designated disk on your computer.
Insert image description here

Next step: Execute the following command in the redis root directory

redis-server.exe redis.windows.conf --maxmemory 200M

Insert image description here

Next step: Commonly used commands to write key-value pairs and enable password login redis operations
Insert image description here

Next step: Register the self-starting service at boot (note: you need to go to the root directory where you installed redis and execute the following cmd command)

#注册安装服务
redis-server --service-install redis.windows.conf --loglevel verbose
#卸载服务
#redis-server --service-uninstall

Insert image description here

Download a visual interface management redis tool: RedisDesktopManager

Insert image description here

If you want to connect to the remote redis cache, as long as the server, port number and password in the table above are configured correctly, you can connect to the redis cache configured on the remote host.

Finally use redis

Install nuget package

Microsoft.Extensions.Caching.StackExchangeRedis

Adding the Redis service to ConfigureServices in Startup.cs will automatically perform dependency injection. The simplest one is as follows:
Insert image description here

Obtain the redis connection object through constructor dependency injection in the controller.

Insert image description here

Cache basic operations

//编辑缓存
cache.SetString(key, value);
//获取缓存
var values = cache.GetString(key);
//更新缓存过期时间
cache.RefreshAsync(key);
//删除缓存
cache.RemoveAsync(key);

If you want to set the cache expiration time, use DistributedCacheEntryOptions, which can set the sliding expiration time (SlidingExpiration), absolute expiration time (AbsoluteExpiration) and absolute expiration time relative to now (AbsoluteExpirationRelativeToNow).

Set sliding expiration time:

var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(20));
cache.SetString(key, value, options);

Finally, you can see the stored value, sliding expiration time and absolute expiration time in the visualization tool. However, the data obtained is string.
Insert image description here

Finish

Guess you like

Origin blog.csdn.net/weixin_49543015/article/details/125801211