abp 缓存使用
作者:互联网
官方文档地址:https://aspnetboilerplate.com/Pages/Documents/Caching
1.先set 后取出
需要在控制器中注入ICacheManager,
[Route("api/[controller]/[action]")]
[ApiController]
public class WeChatController : TestControllerBase
{
private readonly ICacheManager _cacheManager;
private IHttpClientFactory _httpClient;
public WeChatController( IHttpClientFactory httpClient, ICacheManager cacheManager)
{
this._cacheManager = cacheManager;
this._httpClient = httpClient;
}
/// <summary>
/// 获取微信ID
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<dynamic> GetWechatID(string js_code)
{
try
{
using (var client = _httpClient.CreateClient())
{
var url = $"https://api.weixin.qq.com/sns/jscode2session?appid=111&secret=11&js_code={js_code}&grant_type=authorization_code";
//使用注入的httpclientfactory获取client
client.BaseAddress = new Uri(url);
//设置请求体中的内容,并以post的方式请求
var response = await client.GetAsync(url);
//获取请求到数据,并转化为字符串
var result = response.Content.ReadAsStringAsync().Result;
dynamic aa = JsonConvert.DeserializeObject<dynamic>(result);
string session_key = aa.session_key;
string openid = aa.openid;
string bb = PublicMethods.Encrypt(openid);
_cacheManager.GetCache("微信登录").Remove(bb);//先删除之前缓存的数据
_cacheManager.GetCache("微信登录").Set(bb, session_key);//可以理解为定义一个表 然后写入数据 以bb为标识 session_key是要保存的数据
return Json(new { ok = true, msg = "sucess", data = bb });
}
}
catch (Exception e)
{
return Json(new { ok = false, msg = "error", data = e.Message });
}
}
/// <summary>
/// 微信步数解密
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult Decrypt(T微信步数解密 Decrypt)
{
string sessionKey = _cacheManager.GetCache("微信登录").GetOrDefault(Decrypt.wechatid).ToString(); //取出缓存的sessionKey
return Ok(sessionKey);
}
}
2.先get没有则存入数据
[Route("api/[controller]/[action]")]
[ApiController]
public class TablesController : TestControllerBase
{
private readonly ICacheManager _cacheManager;
private string currentUserName;
public TablesController(ICacheManager cacheManager)
{
_cacheManager = cacheManager;
}
[NonAction]
private T医生 Get责任医生By卫生室编号InCache(string _卫生室编号)
{
return _cacheManager
.GetCache("责任医生")
.Get(_卫生室编号, () => Get责任医生By卫生室编号(_卫生室编号)) as T医生;
}
[NonAction]
private T医生 Get责任医生By卫生室编号(string _卫生室编号)
{
using (IDbConnection dbConnection = DapperHelper.CreateLocalConnection())
{
var sql责任医生 = $@"select top 1 *
from 表_医生 where
医生类别='责任医生' and 组织机构编号='{_卫生室编号}'";
return dbConnection.QueryFirstOrDefault<T医生>(sql责任医生);
}
}
}
标签:缓存,string,使用,医生,public,abp,cacheManager,编号,卫生室 来源: https://blog.csdn.net/qq_39569480/article/details/112799673