首页 > 解决方案 > 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 中的数据

但是当我试图读回代码时,它会给出一个空白对象。

代码中未检索到 数据 从 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;
        }
    }

有人能指出我哪里出错了吗?

标签: c#asp.net.netrediswebforms

解决方案


推荐阅读