Redis实践之缓存:.NET CORE实现泛型仓储模式redis接口

第一步:创建ASP.NET Core 6项目

首先,创建一个新的ASP.NET Core 6 Web API项目:

复制代码
dotnet new webapi -n RedisDemo
cd RedisDemo

第二步:安装必要的NuGet包

接下来,安装StackExchange.Redis和Microsoft.Extensions.Caching.StackExchangeRedis包:

复制代码
dotnet add package StackExchange.Redis
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

第三步:配置Redis

在appsettings.json文件中添加Redis的连接字符串:

复制代码
{
  "ConnectionStrings": {
    "Redis": "localhost:6379"
  }
}

第四步:设置依赖注入

在Program.cs文件中配置Redis缓存:

复制代码
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Configure Redis
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

第五步:创建泛型仓储接口和实现

创建一个新的文件夹Repositories,并在其中创建以下接口和类:

IRepository.cs
复制代码
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RedisDemo.Repositories
{
    public interface IRepository<T>
    {
        Task<T> GetAsync(string id);
        Task<IEnumerable<T>> GetAllAsync();
        Task AddAsync(T entity);
        Task UpdateAsync(string id, T entity);
        Task DeleteAsync(string id);
    }
}
RedisRepository.cs
复制代码
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisDemo.Repositories
{
    public class RedisRepository<T> : IRepository<T>
    {
        private readonly IDistributedCache _cache;
        private readonly string _entityName;

        public RedisRepository(IDistributedCache cache)
        {
            _cache = cache;
            _entityName = typeof(T).Name.ToLower();
        }

        public async Task<T> GetAsync(string id)
        {
            var data = await _cache.GetStringAsync($"{_entityName}:{id}");
            return data == null ? default : JsonConvert.DeserializeObject<T>(data);
        }

        public async Task<IEnumerable<T>> GetAllAsync()
        {
            // This is a simplified example. In a real-world scenario, you would need a more sophisticated way to manage keys.
            var keys = Enumerable.Range(1, 100).Select(i => $"{_entityName}:{i}").ToList();
            var result = new List<T>();

            foreach (var key in keys)
            {
                var data = await _cache.GetStringAsync(key);
                if (data != null)
                {
                    result.Add(JsonConvert.DeserializeObject<T>(data));
                }
            }

            return result;
        }

        public async Task AddAsync(T entity)
        {
            var id = Guid.NewGuid().ToString();
            var data = JsonConvert.SerializeObject(entity);
            await _cache.SetStringAsync($"{_entityName}:{id}", data);
        }

        public async Task UpdateAsync(string id, T entity)
        {
            var data = JsonConvert.SerializeObject(entity);
            await _cache.SetStringAsync($"{_entityName}:{id}", data);
        }

        public async Task DeleteAsync(string id)
        {
            await _cache.RemoveAsync($"{_entityName}:{id}");
        }
    }
}

第六步:创建实体类和控制器

创建一个新的文件夹Models,并在其中创建一个实体类:

Product.cs
复制代码
namespace RedisDemo.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

然后创建一个控制器来使用这个仓储:

ProductsController.cs
复制代码
using Microsoft.AspNetCore.Mvc;
using RedisDemo.Models;
using RedisDemo.Repositories;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RedisDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly IRepository<Product> _repository;

        public ProductsController(IRepository<Product> repository)
        {
            _repository = repository;
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Product>> GetProduct(string id)
        {
            var product = await _repository.GetAsync(id);
            if (product == null)
            {
                return NotFound();
            }
            return product;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
        {
            var products = await _repository.GetAllAsync();
            return Ok(products);
        }

        [HttpPost]
        public async Task<ActionResult> CreateProduct(Product product)
        {
            await _repository.AddAsync(product);
            return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
        }

        [HttpPut("{id}")]
        public async Task<ActionResult> UpdateProduct(string id, Product product)
        {
            await _repository.UpdateAsync(id, product);
            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteProduct(string id)
        {
            await _repository.DeleteAsync(id);
            return NoContent();
        }
    }
}

第七步:注册仓储服务

在Program.cs文件中注册仓储服务:

复制代码
builder.Services.AddScoped(typeof(IRepository<>), typeof(RedisRepository<>));

最后一步:运行项目

现在,你可以运行项目并测试API端点了:

复制代码
dotnet run

你可以使用Postman或其他工具来测试API端点,例如:

  • GET /api/products
  • GET /api/products/{id}
  • POST /api/products
  • PUT /api/products/{id}
  • DELETE /api/products/{id}

总结

这样就完成了在ASP.NET Core 6项目中整合使用Redis,并实现泛型接口和仓储模式的完整实例。

相关推荐
zwm26988881519 分钟前
hd 3#负一西送风,能远程启不能远程停
c#
Ai-_Man24 分钟前
Meta Muse还是不可以导出左侧所有对话,只能点进去单条内容导出,方法不对吗?
开发语言·人工智能·ai·小程序·c#·1024程序员节
冬奇Lab2 小时前
一天一个开源项目(第247篇):wxa-runner —— 让小程序在普通浏览器里用微信官方基础库跑起来,直接接 Playwright 做无头 E2E
微信小程序·开源
Lucis__2 小时前
Redis持久化机制解析
redis·缓存·操作系统·文件·非关系型数据库·1024程序员节
supabc1233 小时前
欧盟电子发票(XRechnung/Peppol/ZUGFeRD)踩坑记:用 Python 不装 Java 跑官方校验规则
xml·python·开源·电子发票·1024程序员节
李纲明3 小时前
WordPress 后台登录马上被踢回登录页:Cookie 域、HTTPS、盐值和页面缓存怎么查
运维·缓存·https·php·wordpress·cookie
行者全栈架构师5 小时前
【鸿蒙心迹】让老照片变清晰:HarmonyOS 7.0 图像超分相册工程化落地与 5 个踩坑解法
架构·前端框架·开源
用户094248568035 小时前
第7章:Redis有序集合 ZSet 实战:排行榜与延时任务
redis·架构·源码
码士集团小青6 小时前
面霸篇:高频 Java 基础问题(核心卷一)
linux·服务器·数据库·redis·缓存·1024程序员节
2301_32241428046 小时前
springboot农产品交易平台的设计与实现08055-计算机毕设 原创(免费领源码+部署教程+开发环境)
java·spring boot·redis·mysql·tomcat·maven·mybatis