Redis 在.Net中的使用 ServiceStack.Redis / StackExchange.Redis

NuGet 直接搜索安装 ServiceStack.Redis

代码如下:

using ServiceStack.Redis;
using System; 

namespace redisDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            RedisClient redisClient = new RedisClient("114.67.234.9", 6379);//redis服务IP和端口
            Console.WriteLine(redisClient.Get<string>("lina"));

            Console.ReadKey();
        }
    }
}

超过6000次 提示收费

Helper:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace ServiceStack.Redis
{
    public class RedisHelper : IDisposable
    {
        /// <summary>
        /// 主服务器IP,写操作
        /// </summary>
        //public static string MasterIP = "192.168.10.21";//"127.0.0.1";
        public string MasterIP = RedisHelperConfig.MasterIP;
        /// <summary>
        /// 端口
        /// </summary>
        public int MasterPort = RedisHelperConfig.MasterPort;
        /// <summary>
        /// 数据库 0-15,默认为0
        /// </summary>
        public long Database = RedisHelperConfig.Database;

        /// <summary>
        /// 从服务器IP,读操作
        /// </summary>
        //public static string SlaverIP = "192.168.10.13";//"127.0.0.1";
        public string SlaverIP = RedisHelperConfig.SlaverIP;
        /// <summary>
        /// 端口
        /// </summary>
        public int SlaverPort = RedisHelperConfig.SlaverPort;


        /// <summary>
        /// 默认KEY 存活时间
        /// </summary>
        public static int KeyLiveSecond = RedisHelperConfig.KeyLiveSecond;


        RedisClient master = null;
        RedisClient slaver = null;

        public RedisHelper()
        {
            slaver = new RedisClient(SlaverIP, SlaverPort, null, Database);
            master = new RedisClient(MasterIP, MasterPort, null, Database);
        }

        public RedisHelper(string _MasterIP, int _MasterPort, string _SlaverIP, int _SlaverPort, long _Database)
        {
            MasterIP = _MasterIP;
            MasterPort = _MasterPort;
            SlaverIP = _SlaverIP;
            SlaverPort = _SlaverPort;
            Database = _Database;

            slaver = new RedisClient(SlaverIP, SlaverPort, null, Database);
            master = new RedisClient(MasterIP, MasterPort, null, Database);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                Quit();
            }
        }

        #region 过期操作

        /// <summary>
        /// 获取剩余存货秒
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public long GetTimeToLive(string key)
        {
            long ttlSecs = slaver.Ttl(key);
            return ttlSecs;
        }

        /// <summary>
        /// KEY 存活到 某个时间点
        /// </summary>
        /// <param name="key"></param>
        /// <param name="expireAt"></param>
        /// <returns></returns>
        public bool SetKeyLiveAt(string key, DateTime expireAt)
        {
            return master.ExpireEntryAt(key, expireAt);
        }

        /// <summary>
        /// 设置 key存活 second 秒
        /// </summary>
        /// <param name="key"></param>
        /// <param name="second"></param>
        /// <returns></returns>
        public bool SetKeyLiveAt(string key, int second)
        {
            return master.Expire(key, second);
        }

        /// <summary>
        /// 设置 key存活 TimeSpan秒
        /// </summary>
        /// <param name="key"></param>
        /// <param name="ts"></param>
        /// <returns></returns>
        public bool SetKeyLiveAt(string key, TimeSpan ts)
        {
            return master.Expire(key, (int)ts.TotalSeconds);
        }

        #endregion

        #region 基础操作

        /// <summary>
        /// 更换数据库
        /// </summary>
        /// <param name="db"></param>
        public void ChangeDB(long db)
        {
            Database = db;
            master.Db = Database;
            slaver.Db = Database;
        }
        /// <summary>
        /// 是否包含key的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool ContainsKey(string key)
        {
            return slaver.ContainsKey(key);
        }

        /// <summary>
        /// 移除key的信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            return master.Remove(key);
        }

        /// <summary>
        /// 移除多个key值
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public bool RemoveEntry(params string[] keys)
        {
            return master.RemoveEntry(keys);
        }

        /// <summary>
        /// 重命名
        /// </summary>
        /// <param name="fromName"></param>
        /// <param name="toName"></param>
        public void RenameKey(string fromName, string toName)
        {
            master.RenameKey(fromName, toName);
        }

        /// <summary>
        /// 随便取一个key值
        /// </summary>
        /// <returns></returns>
        public string GetRandomKey()
        {
            return slaver.GetRandomKey();
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        public void Quit()
        {
            slaver.Quit();
            master.Quit();
        }

        #endregion

        #region 基础类型 String int Decimal DateTime

        /// <summary>
        /// 通过匹配方式获取Key信息
        /// </summary>
        /// <param name="keyPattern">
        /// h?llo 匹配 hello
        /// h*llo 匹配 hllo 和 heeeeello 等
        /// h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo
        /// </param>
        /// <returns></returns>
        public List<string> GetKeysPattern(string keyPattern)
        {
            List<string> result = new List<string>();

            byte[][] rlt = slaver.Keys(keyPattern);
            //result = slaver.Get<string>(key);
            for (int i = 0; i < rlt.Length; i++)
            {
                result.Add(FromUtf8Bytes(rlt[i]));
            }

            return result;
        }

        public string GetKeyString(string key)
        {
            string result = "";
            result = slaver.Get<string>(key);

            return result;
        }
        public int? GetKeyInt(string key)
        {
            int? result = 0;
            result = slaver.Get<int?>(key);

            return result;
        }
        public Decimal? GetKeyDecimal(string key)
        {
            Decimal? result = 0M;
            result = slaver.Get<Decimal?>(key);

            return result;
        }
        public DateTime? GetKeyDateTime(string key)
        {
            DateTime? result = null;
            result = slaver.Get<DateTime?>(key);

            return result;
        }



        public long SetKey(string Key, string Value, int second = 0)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            master.Set<string>(Key, Value);
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }
        public long SetKey(string Key, int Value, int second = 0)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            master.Set<int>(Key, Value);
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }
        public long SetKey(string Key, decimal Value, int second = 0)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            master.Set<decimal>(Key, Value);
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();

            return sw.ElapsedMilliseconds;
        }
        public long SetKey(string Key, DateTime Value, int second = 0)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            master.Set<DateTime>(Key, Value);
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();

            return sw.ElapsedMilliseconds;
        }

        #endregion

        #region List

        public long GetListLength(string key)
        {
            long result = 0;
            result = slaver.LLen(key);

            return result;
        }
        public List<string> GetList(string key)
        {
            List<string> result = null;
            result = slaver.GetAllItemsFromList(key);

            return result;
        }
        public List<string> GetList(string key, int bgnIndex, int endIndex)
        {
            List<string> result = null;
            result = slaver.GetRangeFromList(key, bgnIndex, endIndex);

            return result;
        }

        /// <summary>
        /// 返回第index个元素 默认从0开始,-1为倒数第一个
        /// </summary>
        /// <param name="key"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public string GetListIndex(string key, Int32 index)
        {
            string result = "";
            result = FromUtf8Bytes(slaver.LIndex(key, index));

            return result;
        }
        /// <summary>
        /// List从右侧添加对象
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public long ListAddItemR(string Key, string Value, int second = 0)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            master.AddItemToList(Key, Value);
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }
        /// <summary>
        /// List从右侧添加对象集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public long ListAddRangeR(string Key, List<string> Value, int second = 0)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            master.AddRangeToList(Key, Value);
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }
        /// <summary>
        /// List从左侧添加对象集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public long ListAddItemL(string Key, string Value, int second = 0)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            master.PrependItemToList(Key, Value);
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }

        /// <summary>
        /// List从左侧添加对象集合
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public long ListAddRangeL(string Key, List<string> Value, int second = 0)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            master.PrependRangeToList(Key, Value);
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }

        /// <summary>
        /// 清空key 的所有元素
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public long ListRemoveAll(string Key, int second = 0)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            master.RemoveAllFromList(Key);
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }

        /// <summary>
        /// 移除并返回列表 key 的头元素
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public string ListLPOP(string Key, int second = 0)
        {
            string result = "";
            Stopwatch sw = new Stopwatch();
            sw.Start();
            result = FromUtf8Bytes(master.LPop(Key));
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();
            return result;
        }
        /// <summary>
        /// 移除并返回列表 key 的尾元素
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public string ListRPOP(string Key, int second = 0)
        {
            string result = "";
            Stopwatch sw = new Stopwatch();
            sw.Start();
            result = FromUtf8Bytes(master.RPop(Key));
            if (second != 0)
            {
                SetKeyLiveAt(Key, second);
            }
            sw.Stop();
            return result;
        }

        #endregion

        #region Convert

        public byte[] ToUtf8Bytes(string value)
        {
            return Encoding.UTF8.GetBytes(value);
        }


        public string FromUtf8Bytes(byte[] bytes)
        {
            if (bytes != null)
            {
                return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
            }
            return null;
        }

        #endregion


    }
}
View Code

参考 http://www.cnblogs.com/qtqq/p/5951201.html

猜你喜欢

转载自www.cnblogs.com/xiaoshi657/p/9295932.html