How to cache data to Redis in c#

Environmental preparation

First of all, you must install redis! This is the redis I run on docker, which has the same effect as the one installed locally

Visualization tool Redis Desktop Manager.

 

Instructions

The first step is to install the nuget package

Microsoft.Extensions.Caching.StackExchangRedis

 Create an asp.net.core project and inject dependencies before var app = builder.Build();

builder.Services.AddStackExchangeRedisCache(opt =>
{
    opt.Configuration = "localhost";
    opt.InstanceName = "cache1_";
});

Create a new test controller, referencing the dependency just registered

    private readonly IDistributedCache _distributedCache;

    public TestController(IDistributedCache distributedCache)
    {
        _distributedCache = distributedCache;
    }

Then write a get request

    [HttpGet]
    public async Task<ActionResult<Person?>> Test(long id)
    {
        Person? person;
        // 去redis中查找有没有该数据
        string? s = await _distributedCache.GetStringAsync("Person" + id);
        if (s == null)
        {
            Console.WriteLine("数据不存在,从数据库中获取");
            person = MyDbContext.GetById(id);
            Console.WriteLine("把获取的数据存到redis");
            await _distributedCache.SetStringAsync("Person" + id, JsonSerializer.Serialize(person));
        }
        else
        {
            Console.WriteLine("在redis中找到该数据");
            person = JsonSerializer.Deserialize<Person?>(s);
        }

        return person;
    }

Make a breakpoint and see, _distributedCache.GetStringAsync("Person" + id); get a Person1 from redis

For the first acquisition, the data must not exist, after acquisition, pass

await _distributedCache.SetStringAsync("Person" + id,JsonSerializer.Serialize(person));

Store data in redis, view our redis

 Get the same piece of data again, and now you get the data just cached in redis

 The naming of these keys of the cache person here is not fixed, depending on the actual business design, to avoid the same key as other conflicts

var code = "e258771e-aae5-46d6-9b16-fd74812c193c"

Guess you like

Origin blog.csdn.net/weixin_65243968/article/details/131052003