系列文章目錄
鏈接: 【ASP.NET Core】REST與RESTful詳解,從理論到實現
鏈接: 【ASP.NET Core】深入理解Controller的工作機制
鏈接: 【ASP.NET Core】內存緩存(MemoryCache)原理、應用及常見問題解析
文章目錄
- 系列文章目錄
- 前言
- 一、Redis
- 1.1 Redis簡介
- 1.2 常用數據結構
- 1.3 Redis的持久化
- 1.3.1 RDB
- 1.3.2 AOF
- 1.4 常用應用場景
- 1.4.1 緩存
- 1.4.2 計數器
- 1.4.2 訂閱發布
- 二、ASP.NET Core中應用Redis【使用IDistributedCache接口】
- 2.1 安裝依賴
- 2.2 Program.cs 注冊
- 2.3 IDistributedCache
- 2.4 ASP.NET Core Controller中操作Redis
- 2.4.1 獲取緩存
- 2.4.2 設置緩存
- 2.4.3 刪除緩存
- 2.4.4 刷新緩存
- 2.4.5 完整代碼
- 總結
前言
分布式緩存是將緩存數據存儲后供多個外部應用服務器中的服務共享使用。比起內存緩存僅支持本服務使用,分布式緩存擴展多服務器,多應用。故因此得名分布式緩存。本文將介紹ASP.NET Core中如何應用Redis作為分布式緩存服務。
一、Redis
在分享ASP.NET Core中應用Redis作為分布式緩存服務前,先簡單介紹一下Redis。
1.1 Redis簡介
Redis(Remote Dictionary Server)直譯過來就是遠程字典服務。作為一款開源的高性能內存數據結構存儲系統,支持字符串、哈希表、列表等多種數據結構,支持持久化保存功能。并且由于數據存儲在內存中,Redis的讀寫速度遠超傳統關系型數據庫。
1.2 常用數據結構
- 字符串(String)
- 二進制字符串,存儲文本、JSON、數字或二進制圖片數據等
- 哈希(Hash)
- 鍵值對集合,存儲對象結構的數據。
- 列表(List)
- 有序的字符串列表,一般用作存儲消息隊列,或者記錄時間線。
- 集合(Set)
- 無序且唯一的字符串集合,支持交并差操作。因為集合的特性,方便去重的場景使用。
- 有序集合(Sorted Set)
- 類似于普通的集合,但每個成員都關聯了一個分數(score),一般用作排行榜
1.3 Redis的持久化
Redis的持久化分為兩種。一種是RDB,通過將內存中的數據快照寫入磁盤達到數據的保存;另外一種是AOF,Redis 將每個寫操作追加到 AOF 文件的末尾,通過日志的方式記錄操作。
1.3.1 RDB
RDB,既Redis Database,是一種快照持久化機制。是Redis在某一個規則下將某一時刻的內存數據以二進制形式寫入磁盤,生成RDB文件。
RDB的配置項內容在在Redis根目錄下的名為redis.windows-service.conf
的文件里。找到如下的結構
save 900 1 # 900秒內至少1個key被修改
save 300 10 # 300秒內至少10個key被修改
save 60 10000 # 60秒內至少10000個key被修改stop-writes-on-bgsave-error yes #當RDB 快照生成過程中發生錯誤時(如磁盤已滿、權限不足)停止接受新的寫操作,防止數據不一致(默認值:yes)rdbcompression yes #對RDB文件中的字符串對象啟用 LZF 壓縮算法rdbchecksum yes #在RDB文件末尾添加 CRC64 校驗和,用于加載時驗證文件完整性dbfilename dump.rdb
RDB是默認開啟的,執行快照存儲的時候會在根目錄下新建dump.rdb
文件記錄快照。
1.3.2 AOF
AOF,既Append Only File。Redis通過將每個寫操作(如 SET、INCR)追加到 AOF 文件的末尾,實現日志的記錄。顯然這種方式的數據安全性最高。
AOF的配置項內容在在Redis根目錄下的名為redis.windows-service.conf
的文件里。找到如下的結構
appendonly yesappendfilename "appendonly.aof"
AOF并不是默認開啟的。考慮到每一步操作寫操作都會記錄日志。該生成的日志文件會隨著服務的運行變得十分巨大。
1.4 常用應用場景
1.4.1 緩存
將數據庫熱點數據緩存到 Redis,減少數據庫訪問壓力。Redis存儲空值得時候會記錄NULL,自動解決緩存穿透得問題。
1.4.2 計數器
Redis中INCR是用于將存儲在指定鍵中的數值遞增 1 的命令。如果鍵不存在,Redis會先將其初始化為 0,然后再執行 INCR 操作。由于指令是原子性的,這就為我們實現一個計數器提供很好的先決條件。以及接口限流等這種需要使用到計算的功能。
1.4.2 訂閱發布
當出現新的報警通知之類的,發布消息通知所有訂閱的客戶端。
二、ASP.NET Core中應用Redis【使用IDistributedCache接口】
在ASP.NET Core中應用Redis還是比較簡單的,本文應用StackExchangeRedis這個庫來對Redis進行操作。
2.1 安裝依賴
通過這個指令按照StackExchangeRedis包
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
2.2 Program.cs 注冊
在Program.cs中,我們通過AddStackExchangeRedisCache這個靜態擴展方法注冊Redis服務。通過觀察AddStackExchangeRedisCache源碼,我們發現實際上這個擴展方法往DI容器里注冊的是IDistributedCache接口以及實現類RedisCacheImpl。生命周期是singleton。
builder.Services.AddStackExchangeRedisCache(options =>
{options.Configuration = builder.Configuration["Redis:ConnectionStrings"];options.InstanceName = builder.Configuration["Redis:InstanceName"];
});
/// <summary>
/// Adds Redis distributed caching services to the specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="setupAction">An <see cref="Action{RedisCacheOptions}"/> to configure the provided
/// <see cref="RedisCacheOptions"/>.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddStackExchangeRedisCache(this IServiceCollection services, Action<RedisCacheOptions> setupAction)
{ArgumentNullThrowHelper.ThrowIfNull(services);ArgumentNullThrowHelper.ThrowIfNull(setupAction);services.AddOptions();services.Configure(setupAction);services.Add(ServiceDescriptor.Singleton<IDistributedCache, RedisCacheImpl>());return services;
}
2.3 IDistributedCache
IDistributedCache是ASP.NET Core框架提供的一個接口,用于實現分布式緩存,支持多種緩存提供者。也就是說不僅僅是Redis能夠通過這個接口被操作。
這個接口定義很簡單,總的來說就四種方法。Get,Set,Refresh,Remove。以及對應的四個異步方法。
/// <summary>
/// Represents a distributed cache of serialized values.
/// </summary>
public interface IDistributedCache
{/// <summary>/// Gets a value with the given key./// </summary>/// <param name="key">A string identifying the requested value.</param>/// <returns>The located value or null.</returns>byte[]? Get(string key);/// <summary>/// Gets a value with the given key./// </summary>/// <param name="key">A string identifying the requested value.</param>/// <param name="token">Optional. The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>/// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the located value or null.</returns>Task<byte[]?> GetAsync(string key, CancellationToken token = default(CancellationToken));/// <summary>/// Sets a value with the given key./// </summary>/// <param name="key">A string identifying the requested value.</param>/// <param name="value">The value to set in the cache.</param>/// <param name="options">The cache options for the value.</param>void Set(string key, byte[] value, DistributedCacheEntryOptions options);/// <summary>/// Sets the value with the given key./// </summary>/// <param name="key">A string identifying the requested value.</param>/// <param name="value">The value to set in the cache.</param>/// <param name="options">The cache options for the value.</param>/// <param name="token">Optional. The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken));/// <summary>/// Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any)./// </summary>/// <param name="key">A string identifying the requested value.</param>void Refresh(string key);/// <summary>/// Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any)./// </summary>/// <param name="key">A string identifying the requested value.</param>/// <param name="token">Optional. The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>Task RefreshAsync(string key, CancellationToken token = default(CancellationToken));/// <summary>/// Removes the value with the given key./// </summary>/// <param name="key">A string identifying the requested value.</param>void Remove(string key);/// <summary>/// Removes the value with the given key./// </summary>/// <param name="key">A string identifying the requested value.</param>/// <param name="token">Optional. The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>/// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>Task RemoveAsync(string key, CancellationToken token = default(CancellationToken));
}
觀察以上代碼,我們發現返回的RedisValue類型都是byte[]字節數組。這是因為分布式緩存通常運行在獨立的服務,與應用服務器可能使用不同的技術棧。為確保數據能被不同語言或框架正確解析,需要一種通用的數據表示形式。這也是IDistributedCache支持多種緩存提供者的原因。
也就是說實際上從分布式緩存里取到的結果從字節數組需要解析成指定格式的數據,存儲的時候也需要序列化成字節數組。這樣操作尤其麻煩,好在微軟提供了一個名為DistributedCacheExtensions的靜態擴展,內部幫我們通過 Encoding.UTF8.GetBytes(value)和Encoding.UTF8.GetString(data, 0, data.Length)的形式將結果集和字符串形成轉換,相當于少轉了一步。
DistributedCacheExtensions源碼片段【namespace Microsoft.Extensions.Caching.Distributed】
public static Task SetStringAsync(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
{ThrowHelper.ThrowIfNull(key);ThrowHelper.ThrowIfNull(value);return cache.SetAsync(key, Encoding.UTF8.GetBytes(value), options, token);
}public static async Task<string?> GetStringAsync(this IDistributedCache cache, string key, CancellationToken token = default(CancellationToken))
{byte[]? data = await cache.GetAsync(key, token).ConfigureAwait(false);if (data == null){return null;}return Encoding.UTF8.GetString(data, 0, data.Length);
}
2.4 ASP.NET Core Controller中操作Redis
2.4.1 獲取緩存
根據key獲取值,并且轉型
// 嘗試從分布式緩存獲取數據var cachedData = await _distributedCache.GetStringAsync(cacheKey);Movie? movie = null;if (!string.IsNullOrEmpty(cachedData)){// 反序列化緩存數據movie = JsonSerializer.Deserialize<Movie>(cachedData);_logger.LogInformation("從緩存中獲取了電影數據");}
2.4.2 設置緩存
// 緩存未命中,從數據源獲取movie = await _movieAssert.GetMovieAsync(id);if (movie != null){// 設置緩存選項var cacheOptions = new DistributedCacheEntryOptions{// 同時設置絕對過期和滑動過期AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),SlidingExpiration = TimeSpan.FromMinutes(5)};// 序列化并存儲到分布式緩存var serializedData = JsonSerializer.Serialize(movie);await _distributedCache.SetStringAsync(cacheKey, serializedData, cacheOptions);_logger.LogInformation("已將電影數據存入緩存");}
2.4.3 刪除緩存
根據key刪除緩存
await _distributedCache.RemoveAsync(cacheKey);
2.4.4 刷新緩存
一般是碰到需要手動續滑動過期時間的場景才會使用。Redis中如果請求了一個被設置了滑動過期時間的緩存,會自動刷新滑動過期時間的。
await _distributedCache.RefreshAsync(cacheKey);
2.4.5 完整代碼
[Route("api/[controller]")]
[ApiController]
public class MovieController : ControllerBase
{private readonly ILogger<MovieController> _logger;private readonly IMovieAssert _movieAssert;private readonly IDistributedCache _distributedCache;public MovieController(ILogger<MovieController> logger, IMovieAssert movieAssert, IDistributedCache distributedCache = null){_logger = logger;_movieAssert = movieAssert;_distributedCache = distributedCache;}[HttpGet("{id}")]public async Task<ActionResult<Movie?>> Movies(int id){_logger.LogDebug("開始獲取數據");var cacheKey = $"Movie:{id}";// 嘗試從分布式緩存獲取數據var cachedData = await _distributedCache.GetStringAsync(cacheKey);Movie? movie = null;if (!string.IsNullOrEmpty(cachedData)){// 反序列化緩存數據movie = JsonSerializer.Deserialize<Movie>(cachedData);_logger.LogInformation("從緩存中獲取了電影數據");}else{// 緩存未命中,從數據源獲取movie = await _movieAssert.GetMovieAsync(id);if (movie != null){// 設置緩存選項var cacheOptions = new DistributedCacheEntryOptions{// 同時設置絕對過期和滑動過期AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),SlidingExpiration = TimeSpan.FromMinutes(5)};// 序列化并存儲到分布式緩存var serializedData = JsonSerializer.Serialize(movie);await _distributedCache.SetStringAsync(cacheKey, serializedData, cacheOptions);_logger.LogInformation("已將電影數據存入緩存");}}if (movie is null){return NotFound("沒有數據");}return movie;}
}
總結
本文介紹了 Redis 的基本情況及在ASP.NET Core 中借助IDistributedCache接口使用Redis作為分布式緩存的具體操作。
IDistributedCache作為微軟封裝的一個通用的分布式緩存接口,只能說應用了Redis的一些基礎服務。之后我們會討論如何通過直接注冊ConnectionMultiplexer這種方式獲取Redis連接對象,使用Redis的那些高級用法。