Redis的前期准备

     从各种网络资源上,很轻松获得Redis的安装包,然后用命令行进入到redis目录下。执行:redis-server.exe redis.windows.conf   出现如下图标:

 安装正常后,可以再安装一个可视化管理工具:

做一个Redis的小测试程序

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

  <appSettings>
    <!-- redis Start   -->
    <add key="SessionExpireMinutes" value="180" />
    <add key="redis_server_session" value="127.0.0.1:6379" />
    <add key="redis_max_read_pool" value="3" />
    <add key="redis_max_write_pool" value="1" />
    <!--redis end-->
  </appSettings>
</configuration>
View Code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using ServiceStack.Common.Extensions;
using ServiceStack.Redis;
using ServiceStack.Logging;

namespace Weiz.Redis.RedisTest
{
    public class RedisCacheHelper
    {
        private static readonly PooledRedisClientManager pool = null;
        private static readonly string[] redisHosts = null;
        public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);
        public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);

        static RedisCacheHelper()
        {
            var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];

            if (!string.IsNullOrEmpty(redisHostStr))
            {
                redisHosts = redisHostStr.Split(',');

                if (redisHosts.Length > 0)
                {
                    pool = new PooledRedisClientManager(redisHosts, redisHosts,
                        new RedisClientManagerConfig()
                        {
                            MaxWritePoolSize = RedisMaxWritePool,
                            MaxReadPoolSize = RedisMaxReadPool,
                            AutoStart = true
                        });
                }
            }
        }
        public static void Add<T>(string key, T value, DateTime expiry)
        {
            if (value == null)
            {
                return;
            }

            if (expiry <= DateTime.Now)
            {
                Remove(key);

                return;
            }

            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Set(key, value, expiry - DateTime.Now);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }

        }

        public static void Add<T>(string key, T value, TimeSpan slidingExpiration)
        {
            if (value == null)
            {
                return;
            }

            if (slidingExpiration.TotalSeconds <= 0)
            {
                Remove(key);

                return;
            }

            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Set(key, value, slidingExpiration);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }

        }



        public static T Get<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return default(T);
            }

            T obj = default(T);

            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            obj = r.Get<T>(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);
            }


            return obj;
        }

        public static void Remove(string key)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Remove(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
            }

        }

        public static bool Exists(string key)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            return r.ContainsKey(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
            }

            return false;
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Weiz.Redis.RedisTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Redis写入缓存:zhong");
            RedisCacheHelper.Add("zhong", "zhongzhongzhong1234567", DateTime.Now.AddDays(1));
            Console.WriteLine("Redis获取缓存:zhong");
            string str3 = RedisCacheHelper.Get<string>("zhong");
            Console.WriteLine(str3);

            Console.WriteLine("Redis获取缓存:nihao");
            RedisCacheHelper.Add("nihao", "nihaonihaonihao847482", DateTime.Now.AddDays(1));
            string str = RedisCacheHelper.Get<string>("nihao");
            Console.WriteLine(str);


            Console.WriteLine("Redis获取缓存:wei");
            RedisCacheHelper.Add("wei", "春天的气息", DateTime.Now.AddDays(1));
            string str1 = RedisCacheHelper.Get<string>("wei");
            Console.WriteLine(str1);

            Console.ReadKey();
        }
    }
}
View Code

效果:

 数据类型操作:

 /// <summary>
  /// 操作redis的hashtable类型
  /// </summary>
  public static void OperateHash()
  {
      using (RedisClient client = new RedisClient("127.0.0.1", 6379))
      {
          Dictionary<string, string> configDic = new Dictionary<string, string>();
          configDic.Add("config_IP", "localhost");
          configDic.Add("config_Port", "1521");
          configDic.Add("config_serviceName", "orcl");
          configDic.Add("config_userName", "DE_POWERPMS");
          configDic.Add("config_password", "cppepass");
          client.SetRangeInHash("config_info", configDic);
          Dictionary<string, string> testHash = client.GetAllEntriesFromHash("config_info");
          foreach (var item in testHash)
          {
              Console.WriteLine("Hash的key为:{0} 值为:{1}", item.Key, item.Value);
          }
          Console.ReadLine();
      }
  }
View Code
 /// <summary>
        /// 保存数据到Redis缓存中
        /// </summary>
        /// <param name="KeyName">需要保存的键名称,默认保存到redis的第二个数据库中</param>
        /// <param name="configInfo">需要保存的配置信息</param>
        /// <returns>返回保存的结果</returns>
        public static string SaveConfigInfoToRedis(string KeyName, string configInfo)
        {
            using (RedisClient client = new RedisClient("127.0.0.1", 6379))
            {
                if (client == null) return "保存失败!";
                if (client.ContainsKey(KeyName))
                    client.Replace<string>(KeyName, configInfo);
                else
                    client.Set<string>(KeyName, configInfo);
                return "保存成功!";
            }
        }
View Code
  /// <summary>
        /// 操作redis的List类型
        /// </summary>
        public static void OperateList()
        {
            using (RedisClient client = new RedisClient("127.0.0.1", 6379))
            {
                #region List队列操作
                client.EnqueueItemOnList("QueueList", "打印任务1"); //入队
                client.EnqueueItemOnList("QueueList", "打印任务2");
                client.EnqueueItemOnList("QueueList", "打印任务3");
                client.EnqueueItemOnList("QueueList", "打印任务4");
                long q = client.GetListCount("QueueList");
                Console.WriteLine("打印任务按照顺序打印开始");
                for (int i = 0; i < q; i++)
                {
                    Console.WriteLine("QueueList出队值:{0}", client.DequeueItemFromList("QueueList"));
                }
                Console.WriteLine("打印任务按照顺序打印完成");
                #endregion
                #region 栈操作
                client.PushItemToList("StackList", "入栈操作1"); //入栈
                client.PushItemToList("StackList", "入栈操作2");
                client.PushItemToList("StackList", "入栈操作3");
                client.PushItemToList("StackList", "入栈操作4");
                Console.WriteLine("开始出栈");
                long p = client.GetListCount("StackList");
                for (int i = 0; i < p; i++)
                {
                    Console.WriteLine("StackList出栈值:{0}", client.PopItemFromList("StackList"));
                }
                Console.WriteLine("出栈完成");
                Console.ReadLine();
                #endregion
            }
        }
View Code
        /// <summary>
        /// 操作redis的Set类型
        /// </summary>
        public static void OperateSet()
        {
            using (RedisClient client = new RedisClient("127.0.0.1", 6379))
            {
                #region Set操作
                client.AddItemToSet("QQ用户1", "好友A");
                client.AddItemToSet("QQ用户1", "好友B");
                client.AddItemToSet("QQ用户1", "好友C");
                client.AddItemToSet("QQ用户1", "好友D");

                client.AddItemToSet("QQ用户2", "好友C");
                client.AddItemToSet("QQ用户2", "好友F");
                client.AddItemToSet("QQ用户2", "好友G");
                client.AddItemToSet("QQ用户2", "好友D");
                var setunion = client.GetIntersectFromSets("QQ用户1", "QQ用户2");
                Console.WriteLine("QQ用户1和QQ用户2的共同好友为:");
                foreach (var item in setunion)
                {
                    Console.WriteLine(item);
                }
                Console.ReadLine();
                #endregion
            }
        }
View Code
  /// <summary>
  /// 操作redis的SortedSet类型
  /// </summary>
  public static void OperateSortedSet()
  {
   using (RedisClient client = new RedisClient("127.0.0.1", 6379))
   {
    #region Set操作
    client.AddItemToSortedSet("GiftSortedSet", "主播1", 24);
    client.AddItemToSortedSet("GiftSortedSet", "主播2", 564);
    client.AddItemToSortedSet("GiftSortedSet", "主播3", 746);
    client.AddItemToSortedSet("GiftSortedSet", "主播4", 2357);
    client.IncrementItemInSortedSet("GiftSortedSet", "主播2", new Random().Next(200, 500));
    Console.WriteLine("礼物数最多的前三名主播为:");
    foreach (var item in client.GetRangeWithScoresFromSortedSet("GiftSortedSet",1,3))
    {
     Console.WriteLine("名:{"+item.Key+"} 分数:"+item.Value+"");
       
    }
    Console.ReadLine();
    #endregion
   }
  }
View Code
,Best Wish 不负年华
原文地址:https://www.cnblogs.com/shiningleo007/p/14675998.html