net CacheManager 二级缓存 添加 redis string类型的key 不要Hash
在使用.NET CacheManager进行二级缓存时,如果想要添加Redis的string类型的key而不使用Hash键,可以使用CacheManager自带的RedisCacheHandle,并设置UseHashing为false。
以下是一个示例代码:
using CacheManager.Core;
using CacheManager.Redis;
// 设置Redis连接字符串
string redisConnectionString = "localhost:6379";
// 创建CacheManager配置
ConfigurationBuilder builder = ConfigurationBuilder.BuildConfiguration(cfg =>
{
cfg.WithRedisConfiguration("redis", redisConfig =>
{
redisConfig.WithConnectionString(redisConnectionString);
redisConfig.WithDatabase(0);
});
cfg.WithMaxRetries(100)
.WithRetryTimeout(50)
.WithRedisBackplane("redis")
.WithRedisCacheHandle("redis", true)
.WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10));
});
// 创建CacheManager实例
ICacheManager<object> cacheManager = CacheFactory.FromConfiguration<object>(builder);
// 添加缓存项
string cacheKey = "myKey";
string cacheValue = "myValue";
cacheManager.Add(cacheKey, cacheValue);
// 获取缓存项
var result = cacheManager.Get(cacheKey);
在上述代码中,通过配置Redis连接字符串,并将UseHashing设置为false来禁用Hash键。然后可以使用Add方法添加缓存项,并使用Get方法获取缓存项。
需要注意的是,CacheManager还提供了其他缓存操作方法,例如Remove、Clear等,可以根据具体需求进行使用
原文地址: https://www.cveoy.top/t/topic/iHAi 著作权归作者所有。请勿转载和采集!