分布式的緩存可以提高性能和可伸縮性的 ASP.NET Core 應用程序,尤其是托管在雲中或服務器場中時。
什么是分布式的緩存
分布式的緩存由多個應用程序服務器共享,緩存中的信息不存儲在單獨的 Web 服務器的內存中,並且緩存的數據可用於所有應用服務器。這具有幾個優點:
1、所有 Web 服務器上的緩存數據都是一致的。(用戶不會因處理其請求的 Web 服務器的不同而看到不同的結果。)
2、緩存的數據在 Web 服務器重新啟動后和部署后仍然存在。 (刪除或添加單獨的 Web 服務器不會影響緩存。)
3、對數據庫的請求變的更少 。
像其它緩存一樣,分布式緩存可以顯著提高應用的響應速度,因為通常情況下,數據從緩存中檢索比從關系數據庫(或 Web 服務)中檢索快得多。
緩存配置是特定於實現的。 本文介紹如何配置 Redis、 mongoDB 和 SQL Server 分布式緩存。 無論選擇哪一種實現,應用都使用通用的 IDistributedCache
接口與緩存交互。
IDistributedCache 接口
IDistributedCache 接口包含同步和異步方法。 接口允許在分布式緩存實現中添加、檢索和刪除項。 IDistributedCache 接口包含以下方法:
public interface IDistributedCache { //采用字符串鍵並以byte[]形式檢索緩存項(如果在緩存中找到)。 byte[] Get(string key); Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken)); //根據鍵刷新緩存中的項,並重置其過期超時的值(如果有)。 void Refresh(string key); Task RefreshAsync(string key, CancellationToken token = default(CancellationToken)); //根據鍵刪除緩存項。 void Remove(string key); Task RemoveAsync(string key, CancellationToken token = default(CancellationToken)); //使用字符串鍵向緩存中以byte[] 形式添加項 void Set(string key, byte[] value, DistributedCacheEntryOptions options); Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)); }
使用分布式的 Redis 緩存
Redis是一種開源的內存中數據存儲,通常用作分布式緩存。可以在本地使用它,也可以在服務器使用它,在這里,我將把redis服務器安裝在liunx上
1、打開NuGet包管理工具搜索並安裝 Microsoft.Extensions.Caching.Redis 包,或者在程序包管理控制台輸入 PM> Install-Package Microsoft.Extensions.Caching.Redis 然后安裝並配置redis服務器
2、接下來我們來看看怎么使用Redis:
static void Main(string[] args) { RedisCache redisCache = new RedisCache(new RedisCacheOptions() { Configuration="192.168.254.134:6379", InstanceName="test" }); redisCache.SetString("key","value"); var val = redisCache.GetString("key"); Console.WriteLine(val); Console.ReadKey(); }
結果如下:
接下來我們來看看 RedisCache 類里面到底是什么:
public class RedisCache : IDistributedCache, IDisposable { //此處邏輯省略 }
根據上面代碼可以看出,他正是繼承了 IDistributedCache 接口
使用分布式的 MongoDB
MongoDB 是一個基於分布式文件存儲的數據庫
1、打開NuGet包管理工具搜索並安裝 MarkCBB.Extensions.Caching.MongoDB Microsoft.Extensions.Caching.Redis 包,或者在程序包管理控制台輸入 PM> Install-Package MarkCBB.Extensions.Caching.MongoDB 然后安裝並配置mongoDB服務器
2、接下來我們來看看怎么使用MongoDB:
static void Main(string[] args) { MongoDBCache mongoDBCache = new MongoDBCache(new MongoDBCacheOptions() { ConnectionString = "mongodb://192.168.254.135:27017", DatabaseName = "sample", CollectionName = "sample" }); mongoDBCache.Set("username", Encoding.UTF8.GetBytes("jack"), new DistributedCacheEntryOptions() { AbsoluteExpiration = DateTime.Now.AddDays(1) }); var info = mongoDBCache.GetString("username"); Console.WriteLine(info); Console.ReadKey(); }
結果如下:
接下來我們來看看 MongoDBCache 類里面到底是什么:
public class MongoDBCache : IDisposable, IDistributedCache { //此處邏輯省略 }
由上可知,它們都是實現了 IDistributedCache 接口