You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core+Dapper中如何用Redis缓存学生数据

在ASP.NET Core 6中为Dapper查询结果添加Redis缓存

步骤1:配置Redis连接字符串

在appsettings.json中添加Redis的连接配置:

{
  "ConnectionStrings": {
    "DefaultConnection": "你的数据库连接字符串",
    "RedisConnection": "localhost:6379" // 根据你的Redis实例地址调整
  }
}

步骤2:注册Redis服务到依赖注入容器

在Program.cs中添加Redis服务的注册逻辑:

var builder = WebApplication.CreateBuilder(args);

// 注册Redis分布式缓存服务
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("RedisConnection");
    options.InstanceName = "StudentCache_"; // 缓存键前缀,避免不同业务缓存键冲突
});

// 注册仓储服务
builder.Services.AddScoped<IStudentRepository, StudentRepository>();

// 其他现有配置代码...

步骤3:修改StudentRepository实现缓存逻辑

修正现有代码的依赖注入问题,并添加缓存读取、写入逻辑:先从Redis获取缓存,缓存不存在则查询数据库,再将结果写入缓存。

using System.Text.Json;

public class StudentRepository : IStudentRepository
{
    private readonly IConfiguration _configuration;
    private readonly IDistributedCache _distributedCache;

    // 构造函数注入分布式缓存服务
    public StudentRepository(IConfiguration configuration, IDistributedCache distributedCache)
    {
        _configuration = configuration;
        _distributedCache = distributedCache;
    }

    public IDbConnection Connection
    {
        get { return new SqlConnection(_configuration.GetConnectionString("DefaultConnection")); }
    }

    public async Task<IEnumerable<Students>> GetAllStudents()
    {
        const string cacheKey = "AllStudentsList";
        
        // 1. 优先读取Redis缓存
        var cachedData = await _distributedCache.GetStringAsync(cacheKey);
        if (!string.IsNullOrEmpty(cachedData))
        {
            return JsonSerializer.Deserialize<IEnumerable<Students>>(cachedData);
        }

        // 2. 缓存不存在时查询数据库
        using IDbConnection dbConnection = Connection;
        try
        {
            string query = @"SELECT * FROM Students";
            dbConnection.Open();
            var studentList = await dbConnection.QueryAsync<Students>(query);

            // 3. 将查询结果写入Redis缓存,设置过期策略
            var cacheOptions = new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1), // 1小时后绝对过期
                SlidingExpiration = TimeSpan.FromMinutes(30) // 30分钟未访问则滑动过期
            };
            var serializedData = JsonSerializer.Serialize(studentList);
            await _distributedCache.SetStringAsync(cacheKey, serializedData, cacheOptions);

            return studentList;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            dbConnection.Close();
        }
    }
}

步骤4:修正控制器中的拼写错误

原控制器存在接口名称拼写错误,修正后代码如下:

[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
    private readonly IStudentRepository _studentRepository;

    public StudentsController(IStudentRepository studentRepository)
    {
        _studentRepository = studentRepository;
    }

    [HttpGet("GetAllStudents")]
    public async Task<IActionResult> GetQueryStudentAsync()
    {
        var result = await _studentRepository.GetAllStudents();
        return Ok(result);
    }
}

注意事项

  • 若学生数据发生增删改操作,需主动删除对应缓存键,避免出现脏数据
  • 可根据业务调整缓存键命名规则,比如单条学生数据可用Student_{Id}格式
  • 序列化方式可替换为Newtonsoft.Json,需额外引入对应NuGet包

内容的提问来源于stack exchange,提问作者Bami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:07:38