当前位置: 首页 > news >正文

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,并实现泛型接口和仓储模式的完整实例。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 时尚与科技的融合,戴上更轻更悦耳的QCY C30耳夹耳机,随时享受好音乐
  • vue3 实现图片预览组件
  • HTML-DOM模型
  • (一)面试需要掌握的技巧
  • PyQT开发总结
  • 格雷母线电缆头安装方法视频-武汉正向科技
  • C++-第三章:类和对象
  • 使用vite+react+ts+Ant Design开发后台管理项目(三)
  • 我的AI工具箱Tauri版-VideoIntroductionClipCut视频介绍混剪
  • ubuntu24.04 怎么调整swap分区的大小,调整为16G
  • TLC/TK Adv学习笔记1 - Py版本+美化
  • PTA L1-062 幸运彩票
  • One-Class Classification: A Survey
  • 猫头虎分享:Python库 Falcon 的简介、安装、用法详解入门教程
  • 网络通信——OSI七层模型和TCP/IP模型
  • 《用数据讲故事》作者Cole N. Knaflic:消除一切无效的图表
  • CentOS6 编译安装 redis-3.2.3
  • es6要点
  • HTML5新特性总结
  • Java读取Properties文件的六种方法
  • laravel5.5 视图共享数据
  • Meteor的表单提交:Form
  • nginx 配置多 域名 + 多 https
  • October CMS - 快速入门 9 Images And Galleries
  • Sublime Text 2/3 绑定Eclipse快捷键
  • Terraform入门 - 3. 变更基础设施
  • Vue.js-Day01
  • 从PHP迁移至Golang - 基础篇
  • 检测对象或数组
  • 两列自适应布局方案整理
  • 你真的知道 == 和 equals 的区别吗?
  • 前端面试之闭包
  • 首页查询功能的一次实现过程
  • 算法之不定期更新(一)(2018-04-12)
  • Play Store发现SimBad恶意软件,1.5亿Android用户成受害者 ...
  • ​软考-高级-系统架构设计师教程(清华第2版)【第20章 系统架构设计师论文写作要点(P717~728)-思维导图】​
  • #QT(一种朴素的计算器实现方法)
  • #在 README.md 中生成项目目录结构
  • (1)安装hadoop之虚拟机准备(配置IP与主机名)
  • (javascript)再说document.body.scrollTop的使用问题
  • (Redis使用系列) Springboot 使用redis实现接口幂等性拦截 十一
  • (二) 初入MySQL 【数据库管理】
  • (二)【Jmeter】专栏实战项目靶场drupal部署
  • (翻译)Entity Framework技巧系列之七 - Tip 26 – 28
  • (附源码)springboot人体健康检测微信小程序 毕业设计 012142
  • (附源码)springboot猪场管理系统 毕业设计 160901
  • (六)什么是Vite——热更新时vite、webpack做了什么
  • (牛客腾讯思维编程题)编码编码分组打印下标(java 版本+ C版本)
  • (欧拉)openEuler系统添加网卡文件配置流程、(欧拉)openEuler系统手动配置ipv6地址流程、(欧拉)openEuler系统网络管理说明
  • (三分钟)速览传统边缘检测算子
  • (未解决)jmeter报错之“请在微信客户端打开链接”
  • (原創) 如何安裝Linux版本的Quartus II? (SOC) (Quartus II) (Linux) (RedHat) (VirtualBox)
  • ... 是什么 ?... 有什么用处?
  • .halo勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .NET高级面试指南专题十一【 设计模式介绍,为什么要用设计模式】