1 分布式緩存是什么
分布式緩存是由多個應用服務器共享的緩存,通常作為外部服務在訪問它的應用服務器上維護。 分布式緩存可以提高 ASP.NET Core 應用程序的性能和可伸縮性,尤其是在應用程序由雲服務或服務器場托管時。
2 Redis是什么?
Redis是一個高性能的 key-value 數據庫。Redis性能極高,能讀的速度是110000次/s,寫的速度是81000次/s。
3 Redis 安裝
這里我們不具體展開,你可以參考 https://www.runoob.com/redis/redis-install.html 按步驟進行安裝。
4 使用 Redis 分布式緩存
首先,我們簡單的創建一個控制器,實現一個簡單方法,返回當前時間。我們可以看到每次訪問這個接口,都可以看到當前時間。
[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);
}
}
