C# 簡介 C#是微軟公司發佈的一種由C和C++衍生出來的面向對象的編程語言,它不僅去掉了 C++ 和 Java 語言中的一些複雜特性,還提供了可視化工具,能夠高效地編寫程式。 C#是由C和C++衍生出來的一種安全的、穩定的、簡單的、優雅的面向對象編程語言。它在繼承C和C++強大功能的同時去掉了一些 ...
本文通過IDistributedCache
的介面方法,實現Redis與MemoryCache統一幫助類。只需要在配置文件中簡單的配置一下,就可以實現Redis與MemoryCache的切換。
- IDistributedCache
- ICache 介面
- ExpireType枚舉
- CacheType 枚舉
- CacheHelper 緩存幫助類
- CacheHelper 的使用方法
- CacheHelper的使用。
- 總結
IDistributedCache
IDistributedCache 方法:
方法 | 說明 |
---|---|
Get(String) | 獲取具有給定鍵的值。 |
GetAsync(String, CancellationToken) | 獲取具有給定鍵的值。 |
Refresh(String) | 基於緩存中某個值的鍵刷新該值,並重置其可調到期超時(如果有)。 |
RefreshAsync(String, CancellationToken) | 基於緩存中某個值的鍵刷新該值,並重置其可調到期超時(如果有)。 |
Remove(String) | 刪除具有給定鍵的值。 |
RemoveAsync(String, CancellationToken) | 刪除具有給定鍵的值。 |
Set(String, Byte[], DistributedCacheEntryOptions) | 設置具有給定鍵的值。 |
SetAsync(String, Byte[], DistributedCacheEntryOptions, CancellationToken) | 設置具有給定鍵的值。 |
IDistributedCache
還提供了一些擴展方法,本文的幫助類就是通過擴展方法完成的。
IDistributedCache 擴展方法:
方法 | 說明 |
---|---|
GetString(IDistributedCache, String) | 使用指定的鍵從指定的緩存中獲取字元串。 |
GetStringAsync(IDistributedCache, String, CancellationToken) | 使用指定的鍵從指定的緩存非同步獲取字元串。 |
Set(IDistributedCache, String, Byte[]) | 使用指定的鍵設置指定緩存中的位元組序列。 |
SetAsync(IDistributedCache, String, Byte[], CancellationToken) | 使用指定的鍵非同步設置指定緩存中的位元組序列。 |
SetString(IDistributedCache, String, String) | 使用指定的鍵在指定的緩存中設置字元串。 |
SetString(IDistributedCache, String, String, DistributedCacheEntryOptions) | 使用指定的鍵在指定的緩存中設置字元串。 |
SetStringAsync(IDistributedCache, String, String, DistributedCacheEntryOptions, CancellationToken) | 使用指定的鍵在指定的緩存中非同步設置字元串。 |
SetStringAsync(IDistributedCache, String, String, CancellationToken) | 使用指定的鍵在指定的緩存中非同步設置字元串。 |
ICache 介面
ICache介面提供了設置緩存、獲取緩存、刪除緩存和刷新緩存的介面方法。
namespace CacheHelper
{
public interface ICache
{
#region 設置緩存
/// <summary>
/// 設置緩存
/// </summary>
/// <param name="key">緩存Key</param>
/// <param name="value">值</param>
void SetCache(string key, object value);
/// <summary>
/// 設置緩存
/// </summary>
/// <param name="key">緩存Key</param>
/// <param name="value">值</param>
Task SetCacheAsync(string key, object value);
/// <summary>
/// 設置緩存
/// 註:預設過期類型為絕對過期
/// </summary>
/// <param name="key">緩存Key</param>
/// <param name="value">值</param>
/// <param name="timeout">過期時間間隔</param>
void SetCache(string key, object value, TimeSpan timeout);
/// <summary>
/// 設置緩存
/// 註:預設過期類型為絕對過期
/// </summary>
/// <param name="key">緩存Key</param>
/// <param name="value">值</param>
/// <param name="timeout">過期時間間隔</param>
Task SetCacheAsync(string key, object value, TimeSpan timeout);
/// <summary>
/// 設置緩存
/// 註:預設過期類型為絕對過期
/// </summary>
/// <param name="key">緩存Key</param>
/// <param name="value">值</param>
/// <param name="timeout">過期時間間隔</param>
/// <param name="expireType">過期類型</param>
void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType);
/// <summary>
/// 設置緩存
/// 註:預設過期類型為絕對過期
/// </summary>
/// <param name="key">緩存Key</param>
/// <param name="value">值</param>
/// <param name="timeout">過期時間間隔</param>
/// <param name="expireType">過期類型</param>
Task SetCacheAsync(string key, object value, TimeSpan timeout, ExpireType expireType);
#endregion
#region 獲取緩存
/// <summary>
/// 獲取緩存
/// </summary>
/// <param name="key">緩存Key</param>
string GetCache(string key);
/// <summary>
/// 獲取緩存
/// </summary>
/// <param name="key">緩存Key</param>
Task<string> GetCacheAsync(string key);
/// <summary>
/// 獲取緩存
/// </summary>
/// <param name="key">緩存Key</param>
T GetCache<T>(string key);
/// <summary>
/// 獲取緩存
/// </summary>
/// <param name="key">緩存Key</param>
Task<T> GetCacheAsync<T>(string key);
#endregion
#region 刪除緩存
/// <summary>
/// 清除緩存
/// </summary>
/// <param name="key">緩存Key</param>
void RemoveCache(string key);
/// <summary>
/// 清除緩存
/// </summary>
/// <param name="key">緩存Key</param>
Task RemoveCacheAsync(string key);
#endregion
#region 刷新緩存
/// <summary>
/// 刷新緩存
/// </summary>
/// <param name="key">緩存Key</param>
void RefreshCache(string key);
/// <summary>
/// 刷新緩存
/// </summary>
/// <param name="key">緩存Key</param>
Task RefreshCacheAsync(string key);
#endregion
}
}
ExpireType枚舉
ExpireType枚舉標識緩存的過期類型,分為絕對過期
與相對過期
兩個類型。
絕對過期:即自創建一段時間後就過期
相對過期:即該鍵未被訪問後一段時間後過期,若此鍵一直被訪問則過期時間自動延長。
namespace CacheHelper
{
public enum ExpireType
{
/// <summary>
/// 絕對過期
/// 註:即自創建一段時間後就過期
/// </summary>
Absolute,
/// <summary>
/// 相對過期
/// 註:即該鍵未被訪問後一段時間後過期,若此鍵一直被訪問則過期時間自動延長
/// </summary>
Relative,
}
}
CacheType 枚舉
是使用MemoryCache
,還是Redis
,MemoryCache
不支持分散式,Redis
支持分散式。
namespace CacheHelper
{
public enum CacheType
{
/// <summary>
/// 使用記憶體緩存(不支持分散式)
/// </summary>
Memory,
/// <summary>
/// 使用Redis緩存(支持分散式)
/// </summary>
Redis
}
}
CacheHelper 緩存幫助類
namespace CacheHelper
{
public class CacheHelper : ICache
{
readonly IDistributedCache _cache;
public CacheHelper(IDistributedCache cache)
{
_cache = cache;
}
protected string BuildKey(string idKey)
{
return $"Cache_{GetType().FullName}_{idKey}";
}
public void SetCache(string key, object value)
{
string cacheKey = BuildKey(key);
_cache.SetString(cacheKey, value.ToJson());
}
public async Task SetCacheAsync(string key, object value)
{
string cacheKey = BuildKey(key);
await _cache.SetStringAsync(cacheKey, value.ToJson());
}
public void SetCache(string key, object value, TimeSpan timeout)
{
string cacheKey = BuildKey(key);
_cache.SetString(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout)
});
}
public async Task SetCacheAsync(string key, object value, TimeSpan timeout)
{
string cacheKey = BuildKey(key);
await _cache.SetStringAsync(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout)
});
}
public void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType)
{
string cacheKey = BuildKey(key);
if (expireType == ExpireType.Absolute)
{
//這裡沒轉換標準時間,Linux時區會有問題?
_cache.SetString(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout)
});
}
else
{
_cache.SetString(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = timeout
});
}
}
public async Task SetCacheAsync(string key, object value, TimeSpan timeout, ExpireType expireType)
{
string cacheKey = BuildKey(key);
if (expireType == ExpireType.Absolute)
{
//這裡沒轉換標準時間,Linux時區會有問題?
await _cache.SetStringAsync(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout)
});
}
else
{
await _cache.SetStringAsync(cacheKey, value.ToJson(), new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = timeout
});
}
}
public string GetCache(string idKey)
{
if (idKey.IsNullOrEmpty())
{
return null;
}
string cacheKey = BuildKey(idKey);
var cache = _cache.GetString(cacheKey);
return cache;
}
public async Task<string> GetCacheAsync(string key)
{
if (key.IsNullOrEmpty())
{
return null;
}
string cacheKey = BuildKey(key);
var cache = await _cache.GetStringAsync(cacheKey);
return cache;
}
public T GetCache<T>(string key)
{
var cache = GetCache(key);
if (!cache.IsNullOrEmpty())
{
return cache.ToObject<T>();
}
return default(T);
}
public async Task<T> GetCacheAsync<T>(string key)
{
var cache = await GetCacheAsync(key);
if (!string.IsNullOrEmpty(cache))
{
return cache.ToObject<T>();
}
return default(T);
}
public void RemoveCache(string key)
{
_cache.Remove(BuildKey(key));
}
public async Task RemoveCacheAsync(string key)
{
await _cache.RemoveAsync(BuildKey(key));
}
public void RefreshCache(string key)
{
_cache.Refresh(BuildKey(key));
}
public async Task RefreshCacheAsync(string key)
{
await _cache.RefreshAsync(BuildKey(key));
}
}
}
CacheHelper
中,自定義了一個string的擴展方法ToObject<T>()
。ToObject<T>()
擴展方法使用了 Newtonsoft.Json
。
/// <summary>
/// 將Json字元串反序列化為對象
/// </summary>
/// <typeparam name="T">對象類型</typeparam>
/// <param name="jsonStr">Json字元串</param>
/// <returns></returns>
public static T ToObject<T>(this string jsonStr)
{
return JsonConvert.DeserializeObject<T>(jsonStr);
}
CacheHelper 的使用方法
安裝Redis依賴
Redis依賴我使用的是Caching.CSRedis
,安裝依賴:
PM> Install-Package Caching.CSRedis -Version 3.6.90
配置appsettings.json
在appsettings.json中,對緩存進行配置:
"Cache": {
"CacheType": "Memory", // "Memory OR Redis"
"RedisEndpoint": "127.0.0.1:6379" //Redis節點地址,定義詳見 https://github.com/2881099/csredis
},
如果要使用MemoryCache
,CacheType就設置為Memory,如果要使用Redis
,CacheType就設置為Redis。如果設置為Redis的話,還需要配置RedisEndpoint,保證Redis節點可用。
CacheOptions配置
編寫一個名為CacheOptions的類。用於獲取配置文件的配置節內容
namespace CacheHelper
{
public class CacheOptions
{
public CacheType CacheType { get; set; }
public string RedisEndpoint { get; set; }
}
}
IHostBuilder擴展方法UseCache
編寫一個IHostBuilder的擴展方法UseCache,用於註入MemoryCache
或是Redis
public static IHostBuilder UseCache(this IHostBuilder hostBuilder)
{
hostBuilder.ConfigureServices((buidlerContext, services) =>
{
var cacheOption = buidlerContext.Configuration.GetSection("Cache").Get<CacheOptions>();
switch (cacheOption.CacheType)
{
case CacheType.Memory: services.AddDistributedMemoryCache(); break;
case CacheType.Redis:
{
var csredis = new CSRedisClient(cacheOption.RedisEndpoint);
RedisHelper.Initialization(csredis);
services.AddSingleton(csredis);
services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
}; break;
default: throw new Exception("緩存類型無效");
}
});
return hostBuilder;
}
Program.cs中引用
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseCache();
CacheHelper的使用。
public class HomeController
{
readonly ICache _cache;
public HomeController
(
ICache cache,
)
{
_cache = cache;
}
public async Task CacheTest(string key)
{
string cache_value = "hello cache";
//同步方法
_cache.SetCache(key,cache_value );
string v = _cache.GetCache<string>(key);
_cache.RemoveCache(key);
//非同步方法
await _cache.SetCacheAsync(key,cache_value );
string val = await _cache.GetCacheAsync<string>(key);
await _cache.RemoveCacheAsync(key);
}
}
總結
暫無,下次再會!
歡迎大家關註我的微信公眾號,一起進步,一起成長
![](https://img2023.cnblogs.com/blog/93324/202212/93324-20221205182127693-712634750.png)