使用ServiceStack.Redis实现Redis数据读写

User.cs实体类

public class User
{
        public string Name { get; set; }
        public int Id { get; set; }
}

Program.cs

 class Program
    {
        private static readonly RedisHelper redisHelper = new RedisHelper(true);

        private static void Main(string[] args)
        {
            var u = new User { Name = "eric1", Id = 1 };
            redisHelper.Set("user", u); //设置缓存
            u = redisHelper.Get<User>("user");
            Console.WriteLine(u.Name);

            var list = new List<User>
            {
                new User {Name = "永远强大的领导者1", Id = 1},
                new User {Name = "永远强大的领导者2", Id = 2}
            };

            redisHelper.Remove("list1"); //删除缓存
            redisHelper.AddList("list1", list); //添加缓存链表
            redisHelper.AddEntityToList("list1", new User { Name = "永远强大的领导者3", Id = 3 });
            list = redisHelper.GetList<User>("list1").ToList();
            Console.WriteLine(list.Count);

            //队列
            redisHelper.RemoveEntityFromList("list1", list[0]);
            redisHelper.RemoveEntityFromList<User>("list1", it => it.Id == 2);
            list = redisHelper.GetList<User>("list1").ToList();
            Console.WriteLine(list.Count);

            redisHelper.Flushall();
            redisHelper.Dispose();
            Console.ReadLine();
        }
    }

RedisHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.Redis;
using ServiceStack.Redis.Generic;

namespace myRtest
{
    public class RedisHelper : IDisposable
    {
        public RedisClient Redis = new RedisClient("127.0.0.1", 6379, "123456");
        //缓存池
        private PooledRedisClientManager prcm = new PooledRedisClientManager();

        //默认缓存过期时间单位秒
        public int secondsTimeOut = 30 * 60;

        /// 
        ///     构造函数
        /// 
        /// 是否开启缓冲池
        public RedisHelper(bool OpenPooledRedis = false)
        {
            if (OpenPooledRedis)
            {
                prcm = CreateManager(new[] { "[email protected]:6379" }, new[] { "[email protected]:6379" });
                Redis = prcm.GetClient() as RedisClient;
            }
        }

        #region Key/Value存储

        /// 
        ///     设置缓存
        /// 
        /// 
        /// 缓存建
        /// 缓存值
        /// 过期时间,单位秒,-1:不过期,0:默认过期时间
        /// 
        public bool Set<T>(string key, T t, int timeout = 0)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }

            return Redis.Add(key, t);
        }

        /// 
        ///     获取
        /// 
        /// 
        /// 
        /// 
        public T Get<T>(string key)
        {
            return Redis.Get<T>(key);
        }

        /// 
        ///     删除
        /// 
        /// 
        /// 
        public bool Remove(string key)
        {
            return Redis.Remove(key);
        }

        public bool Add<T>(string key, T t, int timeout)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }
            return Redis.Add(key, t);
        }

        #endregion

        #region 链表操作

        /// 
        ///     根据IEnumerable数据添加链表
        /// 
        /// 
        /// 
        /// 
        /// 
        public void AddList<T>(string listId, IEnumerable<T> values, int timeout = 0)
        {
            Redis.Expire(listId, 60);
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(listId, secondsTimeOut);
            }
            IRedisList<T> redisList = iredisClient.Lists[listId];
            redisList.AddRange(values);
            iredisClient.Save();
        }

        /// 
        ///     添加单个实体到链表中
        /// 
        /// 
        /// 
        /// 
        /// 
        public void AddEntityToList<T>(string listId, T Item, int timeout = 0)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(listId, secondsTimeOut);
            }
            IRedisList<T> redisList = iredisClient.Lists[listId];
            redisList.Add(Item);
            iredisClient.Save();
        }

        /// 
        ///     获取链表
        /// 
        /// 
        /// 
        /// 
        public IEnumerable<T> GetList<T>(string listId)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            return iredisClient.Lists[listId];
        }

        /// 
        ///     在链表中删除单个实体
        /// 
        /// 
        /// 
        /// 
        public void RemoveEntityFromList<T>(string listId, T t)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            IRedisList<T> redisList = iredisClient.Lists[listId];
            redisList.RemoveValue(t);
            iredisClient.Save();
        }

        /// 
        ///     根据lambada表达式删除符合条件的实体
        /// 
        /// 
        /// 
        /// 
        public void RemoveEntityFromList<T>(string listId, Func<T, bool> func)
        {
            using (IRedisTypedClient<T> iredisClient = Redis.As<T>())
            {
                IRedisList<T> redisList = iredisClient.Lists[listId];
                T value = redisList.Where(func).FirstOrDefault();
                redisList.RemoveValue(value);
                iredisClient.Save();
            }
        }

        #endregion

        #region 清空Redis所有数据库中的所有key
        public void Flushall()
        {
            Redis.FlushAll();
        }
        #endregion

        //释放资源
        public void Dispose()
        {
            if (Redis != null)
            {
                Redis.Dispose();
                Redis = null;
            }
            GC.Collect();
        }

        /// 
        ///     缓冲池
        /// 
        /// 
        /// 
        /// 
        public static PooledRedisClientManager CreateManager(
            string[] readWriteHosts, string[] readOnlyHosts)
        {
            return new PooledRedisClientManager(readWriteHosts, readOnlyHosts,
                new RedisClientManagerConfig
                {
                    MaxWritePoolSize = readWriteHosts.Length * 5,
                    MaxReadPoolSize = readOnlyHosts.Length * 5,
                    AutoStart = true,
                });
            // { RedisClientFactory = (IRedisClientFactory)RedisCacheClientFactory.Instance.CreateRedisClient("127.0.0.1", 6379) };           
        }
    }
}

运行结果如图:

使用ServiceStack.Redis实现Redis数据读写_第1张图片

你可能感兴趣的:(Nosql之Redis数据库)