高效缓存策略——.NET Core 中基于 Redis 的分布式缓存实现
using StackExchange.Redis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Configuration;
using System;
// 配置接口
public interface ICacheService
{
void Set(string key, object data, TimeSpan expiration);
T Get<T>(string key);
bool Exists(string key);
void Remove(string key);
void Set<T>(string key, T data, DateTimeOffset expirationTime);
}
// 缓存服务实现
public class RedisCacheService : ICacheService
{
private readonly IDistributedCache _cache;
public RedisCacheService(IDistributedCache cache)
{
_cache = cache;
}
public void Set(string key, object data, TimeSpan expiration)
{
byte[] byteData = SerializeObject(data);
_cache.Set(key, byteData, new DistributedCacheEntryOptions().SetAbsoluteExpiration(expiration));
}
public T Get<T>(string key)
{
byte[] data = _cache.Get(key);
if (data == null)
{
return default(T);
}
return DeserializeObject<T>(data);
}
public bool Exists(string key)
{
return _cache.Get(key) != null;
}
public void Remove(string key)
{
_cache.Remove(key);
}
public void Set<T>(string key, T data, DateTimeOffset expirationTime)
{
byte[] byteData = SerializeObject(data);
_cache.Set(key, byteData, expirationTime);
}
// 辅助方法:对象序列化
private byte[] SerializeObject(object obj)
{
// 实现省略,可以使用protobuf、json等方式序列化
throw new NotImplementedException();
}
// 辅助方法:对象反序列化
private T DeserializeObject<T>(byte[] data)
{
// 实现省略,可以使用protobuf、json等方式反序列化
throw new NotImplementedException();
}
}
// 在 Startup.cs 中配置 Redis 缓存服务
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = configuration["Redis:ConnectionString"];
options.InstanceName = "Master";
});
services.AddSingleton<ICacheService, RedisCacheService>();
}
这个代码实例展示了如何在.NET Core应用程序中使用StackExchange.Redis库和Microsoft.Extensions.Caching.Dist
评论已关闭