如何解决Redis 缓存 - 从缓存中读取返回 null
我正在关注 codeproject 中的一篇文章来实现 Redis,这足以满足我的缓存目的。 https://www.codeproject.com/Articles/1120038/A-simple-Csharp-cache-component-using-Redis-as-pro
我可以将数据保存在 Redis 缓存中,如果我通过终端 (redis-cli) 查询缓存,我可以看到与数据一起存储的列表。 设置数据到Redis缓存的代码
private void setDataToRedis()
{
try
{
ICacheProvider _cacheProvider = new RedisCacheProvider();
List<Person> people = new List<Person>()
{
new Person(1,"Joe",new List<Contact>()
{
new Contact("1","123456789"),new Contact("3","234567890")
})
};
_cacheProvider.Remove("Peoples");
_cacheProvider.Set("Peoples",people);
}
catch (Exception ex)
{
throw ex;
}
}
但是当我试图读回代码时,它给出了一个空白对象。
Data not retrieved in code 从Redis读取数据的代码
private void getDataFromRedis()
{
ICacheProvider _cacheProvider = new RedisCacheProvider();
dynamic contacts = "";
if (_cacheProvider.IsInCache("Peoples"))
{
contacts = _cacheProvider.Get<List<Contact>>("Peoples");
}
}
Redis 缓存管理器类
public class RedisCacheProvider : ICacheProvider
{
RedisEndpoint _endPoint;
public RedisCacheProvider()
{
_endPoint = new RedisEndpoint(RedisConfigurationManager.Config.Host,RedisConfigurationManager.Config.Port,RedisConfigurationManager.Config.Password,RedisConfigurationManager.Config.DatabaseID);
}
public void Set<T>(string key,T value)
{
this.Set(key,value,TimeSpan.Zero);
}
public void Set<T>(string key,T value,TimeSpan timeout)
{
using (RedisClient client = new RedisClient(_endPoint))
{
client.As<T>().SetValue(key,timeout);
}
}
public T Get<T>(string key)
{
T result = default(T);
using (RedisClient client = new RedisClient(_endPoint))
{
var wrapper = client.As<T>();
result = wrapper.GetValue(key);
}
return result;
}
public bool Remove(string key)
{
bool removed = false;
using (RedisClient client = new RedisClient(_endPoint))
{
removed = client.Remove(key);
}
return removed;
}
public bool IsInCache(string key)
{
bool isInCache = false;
using (RedisClient client = new RedisClient(_endPoint))
{
isInCache = client.ContainsKey(key);
}
return isInCache;
}
}
有人能指出我哪里出错了吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。