如何使用分佈式緩存(Redis)

1 分佈式緩存是什麼

分佈式緩存是由多個應用服務器共享的緩存,一般做爲外部服務在訪問它的應用服務器上維護。 分佈式緩存能夠提升 ASP.NET Core 應用程序的性能和可伸縮性,尤爲是在應用程序由雲服務或服務器場託管時。html

2 Redis是什麼?

Redis是一個高性能的 key-value 數據庫。Redis性能極高,能讀的速度是110000次/s,寫的速度是81000次/s。redis

3 Redis 安裝

這裏咱們不具體展開,你能夠參考 https://www.runoob.com/redis/redis-install.html 按步驟進行安裝。數據庫

4 使用 Redis 分佈式緩存

首先,咱們簡單的建立一個控制器,實現一個簡單方法,返回當前時間。咱們能夠看到每次訪問這個接口,均可以看到當前時間。api

[Route("api/[controller]")]
[ApiController]
public class CacheController : ControllerBase
{
    [HttpGet]
    public string Get()
    {
        return DateTime.Now.ToString();
    }
}

而後,將Microsoft.Extensions.Caching.Redis的NuGet軟件包安裝到您的應用程序中。緩存

Microsoft.Extensions.Caching.Redis

接着,使用依賴關係注入從應用中引用的服務,在Startup類的ConfigureServices()方法中配置:服務器

public void ConfigureServices(IServiceCollection services)
{
    // install-package Microsoft.Extensions.Caching.Redis
    services.AddDistributedRedisCache(options =>
    {
        options.InstanceName = "";
        options.Configuration = "127.0.0.1:6379";
    });
}

接着,控制器的構造函數中請求IDistributedCache實例分佈式

private IDistributedCache cache;
public RedisCacheController(IDistributedCache cache)
{
    this.cache = cache ?? throw new ArgumentNullException(nameof(cache));
}

最後,在Get方法中使用緩存函數

[HttpGet]
public string Get()
{
    //讀取緩存
    var now = cache.Get("cacheNow");
    if (now == null) //若是沒有該緩存
    {
        cache.Set("cacheNow", Encoding.UTF8.GetBytes(DateTime.Now.ToString()));
        now = cache.Get("cacheNow");
        return Encoding.UTF8.GetString(now);
    }
    else
    {
        return Encoding.UTF8.GetString(now);
    }
}
相關文章
相關標籤/搜索