.Net Core中的内存缓存实现——Redis及MemoryCache(2个可选)方案的实现
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Caching.Memory;
using StackExchange.Redis;
public class RedisCacheService : ICacheService
{
private readonly IMemoryCache _memoryCache;
private readonly ConnectionMultiplexer _redisConnection;
private readonly IDatabase _redisDatabase;
public RedisCacheService(IMemoryCache memoryCache, ConnectionMultiplexer redisConnection)
{
_memoryCache = memoryCache;
_redisConnection = redisConnection;
_redisDatabase = redisConnection.GetDatabase();
}
public void Set(string key, object value, TimeSpan expirationTime)
{
_memoryCache.Set(key, value, expirationTime);
_redisDatabase.StringSet(key, JsonConvert.SerializeObject(value), expirationTime);
}
public T Get<T>(string key)
{
var item = _memoryCache.Get<T>(key);
if (item == null)
{
var value = _redisDatabase.StringGet(key);
if (!value.IsNullOrEmpty)
{
item = JsonConvert.DeserializeObject<T>(value);
_memoryCache.Set(key, item, TimeSpan.FromMinutes(30));
}
}
return item;
}
}
这个代码实例展示了如何同时使用Redis和MemoryCache来实现缓存服务。当从缓存中获取数据时,首先会尝试从内存缓存中获取,如果内存缓存中没有,则会从Redis缓存中获取,并将获取的结果存入内存缓存中,以便下次快速访问。这样的设计既能充分利用内存的速度优势,也能确保数据的持久化存储。
评论已关闭