net CacheManager 二级缓存 获取redis string类型的key 不要Hash 完整代码
下面是使用CacheManager库设置和获取Redis中string类型的key的完整代码示例,不使用哈希进行缓存:
using CacheManager.Core;
using CacheManager.Redis;
class Program
{
static void Main(string[] args)
{
// 配置Redis缓存连接
var cacheConfig = new ConfigurationBuilder()
.WithJsonSerializer() // 使用Json序列化器
.WithRedisConfiguration("redis", config =>
{
config.WithAllowAdmin()
.WithDatabase(0)
.WithEndpoint("localhost", 6379); // Redis服务器地址和端口
})
.WithMaxRetries(100)
.WithRetryTimeout(50)
.WithRedisBackplane("redis") // 使用Redis作为分布式缓存后台
.WithRedisCacheHandle("redis", true) // 使用Redis作为缓存处理程序
.Build();
// 创建缓存管理器
var cacheManager = CacheFactory.FromConfiguration<object>(cacheConfig);
// 设置缓存
var cacheKey = "myKey";
var cacheValue = "myValue";
cacheManager.AddOrUpdate(cacheKey, cacheValue, entry =>
{
entry.WithAbsoluteExpirationRelativeToNow(TimeSpan.FromMinutes(10)); // 设置缓存的过期时间
});
// 获取缓存
var cachedValue = cacheManager.Get(cacheKey);
Console.WriteLine($"Cached Value: {cachedValue}");
Console.ReadLine();
}
}
请确保已经通过NuGet安装了以下包:
- CacheManager.Core
- CacheManager.Core.Configuration.Json
- CacheManager.StackExchange.Redis
此示例使用CacheManager.Redis来处理与Redis缓存的交互,使用Json序列化器进行对象序列化。可以根据实际需求进行修改和优化
原文地址: https://www.cveoy.top/t/topic/iHzy 著作权归作者所有。请勿转载和采集!