基于Redis分布式缓存
1.安装包
使用Redis分布式缓存需要安装Redis的支持包,可以通过nuget命令安装,如下:
install-package Microsoft.Extensions.Caching.StackExchangeRedis
2.在Program.cs文件中注册
builder.Services.AddStackExchangeRedisCache(option => { option.Configuration = "127.0.0.1:6379";//链接地址 option.InstanceName = "myredis";//名字 });
3.在项目API控制中使用
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Distributed; namespace ConsoleWeb.Controllers { [ApiController] [Route("[controller]")] public class CacheController : ControllerBase { public IDistributedCache _cache; public CacheController(IDistributedCache cache) { _cache = cache; } [HttpPost] public async Task<IActionResult> Post() { DistributedCacheEntryOptions options = new DistributedCacheEntryOptions(); //相对过期时间 请求10分钟内有再次请求会再延长十分钟,否则失效 //options.SlidingExpiration = TimeSpan.FromSeconds(10); //2. 绝对过期时间(两种形式) 绝对是请求5秒过期无论使用与否都失效 options.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(80); //options.AbsoluteExpiration= new DateTimeOffset(DateTime.Parse("2022-08-27 16:33:10")); await _cache.SetStringAsync("KeyName", "Cache"); return Ok(); } [HttpGet] public async Task<IActionResult> rGet() { await _cache.GetStringAsync("KeyName"); return Ok(); } [HttpDelete] public async Task<IActionResult> Delete() { await _cache.RemoveAsync("KeyName"); return Ok(); } } }
转载自:https://www.cnblogs.com/xiangshifu/p/17103705.html
补充:https://github.com/catcherwong/Demos/tree/master/src/RedisLockDemo
/// <summary> /// Acquires the lock. /// </summary> /// <returns><c>true</c>, if lock was acquired, <c>false</c> otherwise.</returns> /// <param name="key">Key.</param> /// <param name="value">Value.</param> /// <param name="expiration">Expiration.</param> static bool AcquireLock(string key, string value, TimeSpan expiration) { bool flag = false; try { flag = Connection.GetDatabase().StringSet(key, value, expiration, When.NotExists); } catch (Exception ex) { Console.WriteLine($"Acquire lock fail...{ex.Message}"); flag = true; } return flag; }
static void Main(string[] args) { string lockKey = "lock:eat"; TimeSpan expiration = TimeSpan.FromSeconds(5); //5 person eat something... Parallel.For(0, 5, x => { string person = $"person:{x}"; bool isLocked = AcquireLock(lockKey, person, expiration); if (isLocked) { Console.WriteLine($"{person} begin eat food(with lock) at {DateTimeOffset.Now.ToUnixTimeMilliseconds()}."); } else { Console.WriteLine($"{person} can not eat food due to don't get the lock."); } }); Console.WriteLine("end"); Console.Read(); }
分类:
技术目录九[Net Core]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY