经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Redis » 查看文章
.NET 缓存:内存缓存 IMemoryCache、分布式缓存 IDistributedCache(Redis)
来源:cnblogs  作者:冬先生  时间:2024/5/11 8:55:31  对本文有异议

.NET缓存里分了几类,主要学习内存缓存、分布式缓存

一、内存缓存 IMemoryCache

1、Program注入缓存
  1. builder.Services.AddMemoryCache();
2、相关方法及参数

Get、TryGetValue、GetOrCreate、GetOrCreateAsync、Set、Remove,关键参数是过期时间,GetOrCreate、GetOrCreateAsync是通过委托类型的参数设置的,Set方法可以通过参数直接设置,或者使用MemoryCacheEntryOptions,类型有三种:
(1)AbsoluteExpiration 绝对过期,到期删除
(2)AbsoluteExpirationRelativeToNow 相对当前时间过期,到期删除
(3)SlidingExpiration 滑动过期,时效内访问再延长,未访问到期删除

  1. [Route("api/[controller]/[action]")]
  2. [ApiController]
  3. public class MemoryCacheController : ControllerBase
  4. {
  5. private readonly IMemoryCache _memoryCache;
  6. private readonly string cacheKey = "cache";
  7. public MemoryCacheController(IMemoryCache memoryCache)
  8. {
  9. _memoryCache = memoryCache;
  10. }
  11. [HttpGet]
  12. public string Get()
  13. {
  14. var value = _memoryCache.Get(cacheKey);
  15. return value == null ? "null" : value.ToString();
  16. }
  17. [HttpGet]
  18. public string TryGetValue()
  19. {
  20. if (_memoryCache.TryGetValue(cacheKey, out string value))
  21. return value;
  22. return "null";
  23. }
  24. [HttpGet]
  25. public string GetOrCreate()
  26. {
  27. var value = _memoryCache.GetOrCreate(
  28. cacheKey,
  29. cacheEntry =>
  30. {
  31. cacheEntry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(3);
  32. return "GetOrCreate:" + DateTime.Now.ToString("T");
  33. });
  34. return value;
  35. }
  36. [HttpGet]
  37. public async Task<string> GetOrCreateAsync()
  38. {
  39. var value = await _memoryCache.GetOrCreateAsync(
  40. cacheKey,
  41. cacheEntry =>
  42. {
  43. cacheEntry.SlidingExpiration = TimeSpan.FromSeconds(3);
  44. return Task.FromResult("GetOrCreateAsync:" + DateTime.Now.ToString("T"));
  45. });
  46. return value;
  47. }
  48. [HttpPost]
  49. public void Set()
  50. {
  51. string value = "Set:" + DateTime.Now.ToString("T");
  52. MemoryCacheEntryOptions op = new MemoryCacheEntryOptions();
  53. //绝对到期,到期删除
  54. op.AbsoluteExpiration = DateTimeOffset.Parse("2023-12-31 23:59:59");
  55. //_memoryCache.Set(cacheKey, value, DateTimeOffset.Parse("2023-12-31 23:59:59"));
  56. //相对当前时间过期,到期删除
  57. op.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10);
  58. //_memoryCache.Set(cacheKey, value, TimeSpan.FromSeconds(10));
  59. //滑动过期,时效内访问再延长,未访问到期删除
  60. op.SlidingExpiration = TimeSpan.FromSeconds(10);
  61. _memoryCache.Set(cacheKey, value, op);
  62. }
  63. [HttpDelete]
  64. public void Remove()
  65. {
  66. _memoryCache.Remove(cacheKey);
  67. }
  68. }

二、分布式缓存 IDistributedCache

工欲善其事,必先利其器——>Redis安装

1、Program注入缓存

(1)先安装Nuget:Microsoft.Extensions.Caching.StackExchangeRedis
(2)appsettings.json配置Redis连接

  1. "Redis": "39.107.109.17:6379,password=shenhuak1"

(3)Program注入

  1. //Redis分布式缓存
  2. builder.Services.AddStackExchangeRedisCache(options =>
  3. {
  4. options.Configuration = builder.Configuration["Redis"];
  5. options.InstanceName = "RedisInstance";//实例名,配置后实际的key=InstanceName+key
  6. });
2、相关方法及参数

IDistributedCache 接口提供方法:Get、GetAsync、Set、SetAsync、Refresh、RefreshAsync、Remove、RemoveAsync
以及拓展方法:GetString、GetStringAsync、SetString、SetStringAsync
过期参数跟内存缓存差不多,直接看代码

  1. [Route("api/[controller]/[action]")]
  2. [ApiController]
  3. public class DistributedController : ControllerBase
  4. {
  5. private readonly IDistributedCache _distributedCache;
  6. private readonly string cacheKey = "cache";
  7. public DistributedController(IDistributedCache distributedCache)
  8. {
  9. _distributedCache = distributedCache;
  10. }
  11. [HttpGet]
  12. public string Get()
  13. {
  14. return _distributedCache.GetString(cacheKey);
  15. }
  16. [HttpGet]
  17. public async Task<string> GetAsync()
  18. {
  19. return await _distributedCache.GetStringAsync(cacheKey);
  20. }
  21. [HttpPost]
  22. public void Set()
  23. {
  24. DistributedCacheEntryOptions op = new DistributedCacheEntryOptions();
  25. //绝对过期,到期删除
  26. op.AbsoluteExpiration = DateTimeOffset.Parse("2023-12-31 23:59:59");//op.SetAbsoluteExpiration(DateTimeOffset.Parse("2023-12-31 23:59:59"));
  27. //相对当前时间过期,到期删除
  28. op.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10);//op.SetAbsoluteExpiration(TimeSpan.FromSeconds(10));
  29. //滑动过期,时效内访问再延长,未访问到期删除
  30. op.SlidingExpiration = TimeSpan.FromSeconds(10);//op.SetSlidingExpiration(TimeSpan.FromSeconds(10));
  31. _distributedCache.SetString(cacheKey, DateTime.Now.ToString("T"), op);
  32. }
  33. [HttpPost]
  34. public async Task SetAsync()
  35. {
  36. await _distributedCache.SetStringAsync(cacheKey, DateTime.Now.ToString("T"));
  37. }
  38. [HttpPost]
  39. public void Refresh()
  40. {
  41. _distributedCache.Refresh(cacheKey);
  42. }
  43. [HttpPost]
  44. public async Task RefreshAsync()
  45. {
  46. await _distributedCache.RefreshAsync(cacheKey);
  47. }
  48. [HttpDelete]
  49. public void Remove()
  50. {
  51. _distributedCache.Remove(cacheKey);
  52. }
  53. [HttpDelete]
  54. public async void RemoveAsync()
  55. {
  56. await _distributedCache.RemoveAsync(cacheKey);
  57. }
  58. }
3、总结

非拓展方法是都是通过byte[]字节数组来向Redis存取数据的不方便,大多情况都会自己封装一个helper类。拓展方法虽然用string类型操作,实际存储到Redis是用的Hash类型,无法操作Redis其他类型及功能。
完整功能需要使用其他客户端:StackExchange.Redis、FreeRedis、NRedisStack 等

原文链接:https://www.cnblogs.com/WinterSir/p/17701841.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号