c# - 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;
}
}
但是当我试图读回代码时,它会给出一个空白对象。
代码中未检索到 数据 从 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, value, 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;
}
}
有人能指出我哪里出错了吗?
解决方案
推荐阅读
- angular - 在 Ionic 项目中找不到模块“src/environments/environment”
- javascript - 使用 ajax 和服务器将图像加载到 SPA 时获取 net::ERR_CONNECTION_REFUSED
- wordpress - 如何在 Elementor 中创建编号列表?
- json - _TypeError(类型'列表
' 不是类型 'Map 的子类型 ') - caching - Terraform 模块缓存
- reactjs - 如何解决 React-Redux 的问题(Connect() 中的 mapDispatchToProps() 必须返回一个普通对象。而不是收到未定义的。)
- python - 刮wsj.com
- javascript - 承诺有两个嵌套 Javascript 的 for 循环
- python-3.x - 是否可以在 pypi 包中提供持久数据?
- point-cloud-library - 无法关闭 PCL 可视化工具