流浪のwolf

卷帝

导航

分布式缓存 - 缓存服务器 - redis

如果一般的缓存可以解决问题,就不必使用分布式缓存 ;

 

一般使用分布式缓存 都是使用 redis ;

使用教程:

1. 安装包 Microsoft.Extensions.Caching.StackExchangeRedis

 

2. 注册 redis 服务

  // 注册 redis 缓存
            builder.Services.AddStackExchangeRedisCache(option =>
            {
                option.Configuration = "192.168.33.200";
                option.InstanceName = "test"; /// 起一个名字避免混乱z's
            });

3. 在 controller DI注入接口 

using ClassLibrary1;
using ClassLibrary2;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using WebApplication1.IServices;
using WebApplication1.Utility.SwaggerExt;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.frontAPI))]
    public class HomeController : ControllerBase
    {
        public readonly IDistributedCache distCache;
        public HomeController(IDistributedCache distCache)
        {
            this.distCache = distCache;
        }
        /// <summary>
        /// 测试缓存API
        /// 创建缓存  CreateEntry
        /// 删除缓存  Remove
        /// 获取换粗 TryGetValue  
        /// </summary>
        /// <param name="i"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<Book?>> GetBookById(long id)
        {
            Book? book;
            string s = await distCache.GetStringAsync("Book" + id);
            if(s == null)
            {
                // 没有缓存 从数据库获取信息
                book = await MyDbContext.GetByIdAsync(id);
                // 存入缓存  SetStringAsync(key,string)
                distCache.SetStringAsync("Book" + id,JsonSerializer.Serialize(book));  
            }else
            {
                // 从缓存里面获取到了 s 反序列化得到
                book = JsonSerializer.Deserialize<Book?>(s);
            }

            if(book == null)
            {
                return NotFound("不存在");
            }else
            {
                return Ok(book);
            }
        }
    }
}

 

posted on 2023-10-24 19:31  流浪のwolf  阅读(5)  评论(0编辑  收藏  举报