基于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();  
} 

 

posted @ 2023-07-04 17:52  vba是最好的语言  阅读(50)  评论(0编辑  收藏  举报