关于C#操作redis公共类,网上有很多版本,每个版本我都看了,发觉还是不够完美,都存在一个问题,只能操作单一的缓存数据库
redis指令支持上,这里可以自己去扩展,下面分享下我近期封装的一个redis操作类
要用到ServiceStack.Redis V3版,不要用V4 ,v4已经商业化了,有6000次限制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;

namespace ZhengXin.Tools
{
    public class RedisUtils
    {
        /// <summary>
        /// 默认过期时间 为秒
        /// </summary>
        private static int secondsTimeOut = 30 * 60;

        #region @Royal改进部分,能操作16个库

        private static readonly Dictionary<int, PooledRedisClientManager> pools = new Dictionary<int, PooledRedisClientManager>();

        static RedisUtils()
        {
            string path = ConfigHelper.GetConfigKeyValue("RedisPath");
            string[] readWriteHosts = new string[] { path };
            string[] readOnlyHosts = new string[] { path };
//初始化16个缓存库 for (int i = 0; i <= 15; i++) { var model = new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 50, // “写”链接池链接数 MaxReadPoolSize = 50, // “读”链接池链接数 AutoStart = true, }, i, 100, 20); pools.Add(i, model); } } public static PooledRedisClientManager ChooseRedisInstance(int database) { if (database > 16) return pools[0]; return pools[database]; } public static void Lpush(string key, string value, int database = 0) { using (IRedisClient redis = ChooseRedisInstance(database).GetClient()) { redis.PushItemToList(key, value); } } public static string Lpop(string key, int database = 0) { using (IRedisClient redis = ChooseRedisInstance(database).GetClient()) { return redis.PopItemFromList(key); } } public static List<string> List(string key, int database = 0) { using (IRedisClient redis = ChooseRedisInstance(database).GetClient()) { return redis.GetAllItemsFromList(key); } } public static bool ItemSet<T>(string key, T t, int timeout = 0, int db = 2) { using (IRedisClient RClient = ChooseRedisInstance(db).GetClient()) { if (timeout >= 0) { if (timeout > 0) { secondsTimeOut = timeout; } } return RClient.Add<T>(key, t, TimeSpan.FromMinutes(secondsTimeOut)); } } public static T ItemGet<T>(string key, int db = 2) where T : class { using (IRedisClient redis = ChooseRedisInstance(db).GetClient()) { return redis.Get<T>(key); } } } }