AbpVnext使用分布式IDistributedCache Redis缓存(自定义扩展方法)
AbpVnext使用分布式IDistributedCache缓存from Redis(带自定义扩展方法)
我的依赖包的主要版本以及Redis依赖如下
1:添加依赖
<PackageReference Include="Volo.Abp.Caching.StackExchangeRedis" Version="3.0.5" /> <ItemGroup>
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="Microsoft.Extensions.PlatformAbstractions" Version="1.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.9.5" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="8.2.0" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
<PackageReference Include="SqlSugar.IOC" Version="1.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.5.1" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUi" Version="5.5.1" />
<PackageReference Include="Volo.Abp.AspNetCore" Version="3.0.5" />
<PackageReference Include="Volo.Abp.AspNetCore.Authentication.JwtBearer" Version="3.0.5" />
<PackageReference Include="Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared" Version="3.0.5" />
<PackageReference Include="Volo.Abp.AspNetCore.Serilog" Version="3.0.5" />
<PackageReference Include="Volo.Abp.Autofac" Version="3.0.5" />
<PackageReference Include="Volo.Abp.UI.Navigation" Version="3.0.5" />
//添加AbpVnext分布式redis缓存依赖包
<PackageReference Include="Volo.Abp.Caching.StackExchangeRedis" Version="3.0.5" />
</ItemGroup>
2:配置信息。默认在appsetting.json中配置即可,格式如下:
"Redis": { //Redis:Configuration
"IsEnabled": "true",
//该服务将会吧数据存储在DB7的数据库中
"Configuration": "171.74.78.153:6379,password=9966686@,defaultdatabase=7"
}
3:在hosting模块中添加依赖
using Volo.Abp.Caching.StackExchangeRedis; namespace GDBS.MonitoringService.HttpApi.Hosting
{
[DependsOn(
typeof(AbpAutofacModule),
typeof(AbpAspNetCoreMvcModule),
typeof(AbpAspNetCoreAuthenticationJwtBearerModule)
, typeof(IdentityEntityFrameworkCoreModule)
, typeof(MonitoringHttpApiModule)
, typeof(MonitoringApplicationContractsModule)
, typeof(SharedToolKitsModule)
, typeof(JketSharedDomainModule)
, typeof(AbpCachingStackExchangeRedisModule)//这里新增依赖模块
)]
public class MonitoringHttpApiHostingModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
//测试时下面配置了还出不来,写入没有效果??这里就直接在配置文件中处理了。
//service.AddStackExchangeRedisCache(redisoptions =>
//{
// redisoptions.Configuration = configuration["Redis:Configuration"];
// redisoptions.ConfigurationOptions = new StackExchange.Redis.ConfigurationOptions
// {
// ConnectTimeout = 10
// //EndPoints=new StackExchange.Redis.EndPointCollection { // //}
// };
//});
}
}
4:Controller中的主要代码
namespace GDBS.ProvincialLevelService.HttpApi.Controller
{
/// <summary>
/// ProvincialLevelService 省级服务
/// </summary>
[Authorize]
[Area("ProvincialLevelService")]
[Route("api/ProvincialLevelService/[Controller]")]
public class ProvincialLevelDataInfoController : AbpController
{
private readonly IBridgeTestDataService _service;
private readonly IBridgeTestDataService _service;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IHttpContextAccessor _httpContext;
private readonly IFilesInfoService _filesInfoservice; /// <summary>
///
/// </summary>
/// <param name="service"></param>
/// <param name="httpClientFactory"></param>
/// <param name="httpContext"></param>
public ProvincialLevelDataInfoController(IBridgeTestDataService service, IHttpClientFactory httpClientFactory, IHttpContextAccessor httpContext, IFilesInfoService filesInfoservice)
{
_service = service;
_httpClientFactory = httpClientFactory;
_httpContext = httpContext;
_filesInfoservice = filesInfoservice;
} /// <summary>
/// TestRedisAddString
/// </summary>
/// <param name="key"></param>
/// <param name="redisvalue"></param>
/// <returns></returns>
[HttpGet("TestRedisAddString")]
[AllowAnonymous]
public async Task<OutputDto> TestRedisAddString(string key, string redisvalue)
{
try
{
await _service.DoTestRedis(key, redisvalue);
return OutputDto.ToResultSuccess(msg: "ok");
}
catch (Exception ex)
{
return OutputDto.ToResultFail(ex.Message);
}
}
}
}
5:Application中,通常我们在这里来注入分布式接口
using Microsoft.Extensions.Caching.Distributed;
namespace GDBS.ProvincialLevelService.Application.AppService
{
public class BridgeTestDataService : ApplicationService, IBridgeTestDataService
{
private readonly IDistributedCache _distributedCache;
public BridgeTestDataService(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
} public async Task<string> DoTestRedis(string key, string redisvalue)
{
try
{
await _distributedCache.SetStringAsync(key,redisvalue);
return "ok";
}
catch (Exception ex)
{
return $"错误{ex.Message}";
}
}
}
}
6:为了方便直接在Controller中注入测试,通常我们需要在Application中注入使用
/// <summary>
/// _cacheServer 通常我们在Application里面注册,这里只是测试
/// </summary>
private readonly IDistributedCache _cacheServer;
public ProvincialLevelDataInfoController(IDistributedCache cacheServer)
{
_cacheServer = cacheServer;
}
/// <summary>
/// TestRedisAddString
/// </summary>
/// <param name="key"></param>
/// <param name="redisvalue"></param>
/// <param name="ab_hd">true绝对过期,false:滑动过期</param>
/// <returns></returns>
[HttpGet("TestRedisAddString2")]
[AllowAnonymous]
public async Task<OutputDto> TestRedisAddString2(string key, string redisvalue, bool ab_hd = true)
{
try
{
await _cacheServer.SetStringAsync(key, redisvalue, RedisPolicyHelper.GetRedisProcily(ab_hd,60));
return OutputDto.ToResultSuccess(msg: "ok");
}
catch (Exception ex)
{
return OutputDto.ToResultFail(ex.Message);
}
}
7:分布式缓存的策略,使用绝对还是滑动过期,不使用策略就默认为长期保存,可以使用控制方法
using Microsoft.Extensions.Caching.Distributed;
using System;
namespace GDBS.Shared.ToolKits.Tool
{
public class RedisPolicyHelper
{
/// <summary>
/// 使用绝对还是滑动过期,不使用策略就默认为长期保存
/// </summary>
/// <param name="ab_hd">true绝对过期; false:滑动过期</param>
/// <param name="Seconds">默认60秒过期</param>
/// <returns></returns>
public static DistributedCacheEntryOptions GetRedisProcily(bool ab_hd, int Seconds = 60)
{
var policy = new DistributedCacheEntryOptions();
Seconds = Seconds <= 1 ? 60 : Seconds;
if (ab_hd)
policy.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(Seconds);
else
policy.SlidingExpiration = TimeSpan.FromSeconds(Seconds);
return policy;
}
}
}
8:自定义分布式缓存扩展方法
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.Extensions.Caching.Distributed;
namespace GDBS.Shared.ToolKits
{
public static class RedisDistributeExtension
{
/// <summary>
/// 自定义IDistribute 分布式扩展方法 jason 同步方法
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <param name="cache"></param>
/// <param name="key"></param>
/// <param name="handler"></param>
/// <returns></returns>
public static TModel RedisGetOrCreate<TModel>(this IDistributedCache cache, string key, Func<DistributedCacheEntryOptions, TModel> handler)
{
TModel t;
string vs = cache.GetString(key);
if (string.IsNullOrEmpty(vs))
{
var options = new DistributedCacheEntryOptions();
t = handler.Invoke(options);
cache.SetString(key, JsonConvert.SerializeObject(t), options);
}
else
{
t = JsonConvert.DeserializeObject<TModel>(vs);
}
return t;
}
/// <summary>
/// 自定义IDistribute 分布式扩展方法 jason 异步方法
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <param name="cache"></param>
/// <param name="key"></param>
/// <param name="handler"></param>
/// <returns></returns>
public static async Task<TModel> RedisGetOrCreateAsync<TModel>(this IDistributedCache cache, string key, Func<DistributedCacheEntryOptions, Task<TModel>> handler)
{
TModel t;
var vs = await cache.GetStringAsync(key);
if (string.IsNullOrEmpty(vs))
{
var options = new DistributedCacheEntryOptions();
t = await handler.Invoke(options);
await cache.SetStringAsync(key, JsonConvert.SerializeObject(t), options);
}
else
{
t = JsonConvert.DeserializeObject<TModel>(vs);
}
return t;
}
}
}
9:测试自定义扩展方法,Controller中的主要code。
/// <summary>
/// 自定义分布式缓存的扩展方法,没有缓存就设置缓存,有就直接获取
/// </summary>
/// <param name="key"></param>
/// <param name="redisvalue"></param>
/// <param name="ab_hd"></param>
/// <returns></returns>
[HttpGet("TestRedisAddString3")]
[AllowAnonymous]
public async Task<OutputDto> TestRedisAddString3(string key, string redisvalue, bool ab_hd = true)
{
try
{
await _cacheServer.RedisGetOrCreateAsync<string>(key, (options) =>
{
options.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(30);
return Task.Factory.StartNew(() =>
{
return $"_cacheServer.RedisGetOrCreateAsync获取或者设置缓存的方法:{redisvalue},时间:{DateTime.Now}";
});
});
return OutputDto.ToResultSuccess(msg: "ok");
}
catch (Exception ex)
{
return OutputDto.ToResultFail(ex.Message);
}
}
10:调用自定义分布式扩展方法


11:测试结果部分主要截图:


12:公司一微服务系统中有多个服务,我们将不同的服务缓存数据将来存储在不同的Redis数据库中

好了今天就先到这里,下次有时间再更新,自学AbpVnext过程中难免会有一些bug或者不合理的地方,欢迎大家多多指教留言!!!
AbpVnext使用分布式IDistributedCache Redis缓存(自定义扩展方法)的更多相关文章
- Jquery自定义扩展方法(二)--HTML日历控件
一.概述 研究了上节的Jquery自定义扩展方法,自己一直想做用jquery写一个小的插件,工作中也用到了用JQuery的日历插件,自己琢磨着去造个轮子--HTML5手机网页日历控件,废话不多说,先看 ...
- MVC缓存03,扩展方法实现视图缓存
关于缓存,先前尝试了: ● 在"MVC缓存01,使用控制器缓存或数据层缓存"中,分别在控制器和Data Access Layer实现了缓存 ● 在"MVC缓存02,使用数 ...
- Jquery自定义扩展方法(一)
jquery是一款流行的JS框架,自定义JS方法,封装到Jquery中,调用起来也挺方便的,怎么写Jquery扩展方法那,网上翻阅了一部分代码,其实也挺简单的: 方式一: (jQuery.fn.set ...
- WinForm TextBox自定义扩展方法数据验证
本文转载:http://www.cnblogs.com/gis-crazy/archive/2013/03/17/2964132.html 查看公司项目代码时,存在这样一个问题:winform界面上有 ...
- Unity中自定义扩展方法
问题背景 在使用unity开发过程中,通常会遇到一种情况,比如说给物体重新赋值坐标的问题, Transfrom tran: ,pos_y=,pos_z=; tran.position=new Vect ...
- Layui数据表格加入自定义扩展方法(重新渲染Render当前页数据)
具体开发中遇到的问题如下, 数据表格的重新渲染或重新加载会导致当前操作的分页 或 配置被清空.我正在操作第5页,重新渲染后就回到了最原始第1页. 需要达到的效果是: 不调用接口,仅仅只是从table. ...
- C# 实现和调用自定义扩展方法
定义和调用扩展方法 定义一个静态类以包含扩展方法.该类必须对客户端代码可见. 将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性. 该方法的第一个参数指定方法所操作的类型:该参数必须以 t ...
- Swift学习(二):自定义扩展方法(Extensions)
扩展就是向一个已有的类.结构体或枚举类型添加新功能(functionality) 扩展可以 添加计算型属性和计算静态属性 定义实例方法和类型方法 提供新的构造器 定义下标 定义和使用新的嵌套类型 使一 ...
- jQuery 自定义扩展,与$冲突处理
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
随机推荐
- Lniux上的tomcat部署web项目路径问题
一.项目路径及部署.启动位置 1.在tomcat下部署应用,部署路径:一般直接部署在tomcat/webapps/ROOT下即可.2.默认访问路径:tomcat的默认访问路径为webapps/ROOT ...
- Deepin 20.2.2 /UOS 20.2 添加ppa源
由于 工作需要,需要通过PPA安装一些优质的软件包,但是 Deepin 默认不支持PPA源 解决方法 由于Deepin/Uos系统默认是没有安装PPA的那么我们得先安装PPA来支持"add- ...
- 第十四篇 -- QMainWindow与QAction(清空-全选-撤销-重做-关闭-语言选择)
效果图: 这次添加了关闭-撤销-重做-全选-清空等功能,并添加了字体和字体大小选择.基本方法跟前面几篇类似. ui_mainWindow.py # -*- coding: utf-8 -*- # Fo ...
- Pelles C 五光十色中的一抹经典
我只是一个程序员,没有多少文化修养,根本不会组织出多么精彩动人的辞藻,所以废话不多说,开整. 前段时间,我开始了自己的毕业设计项目,项目的主题和内容是围绕数码防伪追溯原理制作一个识别装置,而这个装置并 ...
- 算法优化---素数(质数)(Java版)
4.1优化算法-----输出素数 最简代码请直接移步文末 原代码:https://www.cnblogs.com/Tianhaoblog/p/15077840.html 对应优化如下 优化一:在遍历内 ...
- Python - dict 字典常见方法
字典详解 https://www.cnblogs.com/poloyy/p/15083781.html get(key) 作用 指定键,获取对应值 两种传参 dict.get(key):键存在则返回对 ...
- 学会这十招,轻松搜索github优质项目
大家好,我是青空. 今天我想给大家分享一下使用 GitHub 的一些心得体会.之前我是在分享 GitHub上的一些开源项目,通过这段时间的收集工作,我积累了一些相关的经验在这里分享给大家. 我做了一个 ...
- vue实现单点登录的N种方式
最近项目停工了,RageFrame的学习暂时告一段落,这一篇给大家分享下有关单点登录的相关知识,并提供一些demo给大家参考,希望对想了解的朋友有一些帮助. 话不多说,先上原理(借鉴地址:https: ...
- mitmproxy第一次尝试-猿人学第九题
启动 mitmdump -s http_proxy.py -p 9000 替换js代码 # -*- coding: utf-8 -*- import re main_url = 'http://mat ...
- linux signal信号(SIGHUP、SIGINT、SIGQUIT、SIGILL、SIGTRAP、SIGABRT...........................)
SIGHUP /* hangup */ ~~~~~~ SIGHUP,hong up ,挂断.本信号在用户终端连接(正常或非正常)结束时发出, 通常是在终端的控制进程结束时, 通知 ...