Redis作为一种高性能的内存数据库,能够有效地减少数据库的压力,并提升应用的访问速度。本方案将详细说明如何在ABP框架中配置Redis缓存,并提供相应的代码示例。
如果想要在ABP框架调用Redis的缓存。需要如下步骤
Step1:安装Microsoft.Extensions.Caching.StackExchangeRedis
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
Step2:在启动Model配置Redis服务信息
接下来,我们需要在ABP框架中配置Redis缓存。一般来说,我们会在你项目对应的启动项的HostModule文件中进行配置。
using Medallion.Threading;
using Medallion.Threading.Redis;
namespace AbpDemo
{
public class MyModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
var configuration = context.Services.GetConfiguration();
context.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = configuration["Redis:Configuration"]; // Redis服务器地址
options.InstanceName = "NumBdInstance"; // 实例名称
});
}
}
}
Step3:编辑appsettings.json新增Redis的服务地址
因为上面的代码是从配置读取的Redis,所以我们要对应修改配置文件,新增下面一条记录(应该是Redis服务器地址:端口号)
"Redis": {
"Configuration": "127.0.0.1:6379"
}
Step4:配置完成了,下面开始使用缓存
我们可以在应用中使用缓存。可以通过依赖注入将IDistributedCache引入到服务或控制器中,下面是一个使用例子
namespace Org.NumBd.Zppr
{
public class ZpprAppService : ApplicationService, IZpprAppService
{
private readonly IDistributedCache _cache;
public ZpprAppService(IDistributedCache cache)
{
_cache = cache;
}
public async Task<IResponseOutput<Zppf021Dto>> GetAsync(Guid id)
{
string cacheKey = $"Zppf021-{id}";
//按照指定KEY从缓存取值,如果存在直接返回
string cachedProduct = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cachedProduct))
{
var cachres = JsonConvert.DeserializeObject<Zppf021Dto>(cachedProduct); // 如果缓存中存在返回缓存的值
return ResponseOutput.Ok(cachres);
}
//缓存不存在,去DB取值,并将结果存到缓存
var Entity = await _zPPF021Repository.GetAsync(id);
var res = ObjectMapper.Map<ZPPF021, Zppf021Dto>(Entity);
await _cache.SetStringAsync(cacheKey, JsonConvert.SerializeObject(res));
return ResponseOutput.Ok(res);
}
}
}