Redis帮助类

using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp7
{
    public class RedisHelper
    {
        public static readonly RedisHelper Instance = new RedisHelper();

        private readonly object _syncRoot = new object();

        /// <summary>
        /// redis分布式锁
        /// </summary>
        private Redlock.CSharp.Redlock dlm_redlock { get; set; }
        private RedisHelper()
        {

        }

        public ConnectionMultiplexer RedisConnectionManager
        {
            get; private set;
        }

        private IDatabase _redisDatabase;

        public IDatabase RedisDatabase
        {
            get
            {
                return this._redisDatabase;
            }
            set
            {
                this._redisDatabase = value;
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="configuration"></param>
        public void Init(string configuration)
        {
            try
            {
                RedisConnectionManager = ConnectionMultiplexer
                    .Connect(configuration);
                RedisDatabase = this.RedisConnectionManager.GetDatabase();

                List<ConnectionMultiplexer> listCM = new List<ConnectionMultiplexer>();
                foreach (var item in configuration.Split(','))
                {
                    listCM.Add(ConnectionMultiplexer.Connect(item));
                }
                dlm_redlock = new Redlock.CSharp.Redlock(listCM[0]);
            }
            catch (Exception ex)
            {
               // LogHelper.WriteLog(ex.Message, ex);
                throw ex;
            }
        }
        /// <summary>
        /// 反初始化
        /// </summary>
        public void UnInit()
        {
            RedisDatabase = null;
            if (RedisConnectionManager != null)
                RedisConnectionManager.Dispose();
        }

        public void HashIncrement(string mapName, string key)
        {
            RedisDatabase.HashIncrement(mapName, key);
        }

        //public void StringIncrement(string key)
        //{
        //    RedisDatabase.StringIncrement(key);
        //}

        /// <summary>
        /// 以分布式锁的方式读取写入值到redis
        /// </summary>
        /// <param name="lockKey">锁定资源的key</param>
        /// <param name="action">具体操作</param>
        /// <param name="throwExecption">未获取到分布式锁是否抛出异常默认为是</param>
        public void LockAction(string lockKey, Action<IDatabase> action, bool throwExecption = true)
        {
            if (action == null)
            {
                throw new ArgumentNullException("参数action空异常");
            }
            Redlock.CSharp.Lock lockObject;
            var locked = GetLock(lockKey, out lockObject);
            //没有获取到锁 则进行等待,最多等待5秒
            int total = 0;
            Random rdm = new Random();
            int sleepTime = 0;
            while (!locked)
            {
                sleepTime = rdm.Next(100, 200);
                //等待100毫秒,重新获取
                Thread.Sleep(sleepTime);
                total += sleepTime;
                locked = GetLock(lockKey, out lockObject);
                if (total > 11000)
                {
                    break;
                }
            }
            if (!locked && throwExecption)
            {
                throw new Exception("获取redis分布式锁失败");
            }
            if (locked)
            {
                try
                {
                    action(RedisDatabase);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //释放分布式锁
                    dlm_redlock.Unlock(lockObject);
                }
            }
        }
        /// <summary>
        /// 获取分布式锁
        /// </summary>
        /// <param name="lockKey"></param>
        /// <param name="lockObject">锁对象</param>
        /// <returns>获取锁是否成功</returns>
        private bool GetLock(string lockKey, out Redlock.CSharp.Lock lockObject)
        {
            return dlm_redlock.Lock(
                  "RedLock_" + lockKey,
                  new TimeSpan(0, 0, 10),//最多锁10s 则自动释放锁
                  out lockObject
              );
        }

        public void HSet(string mapName, string key, string value)
        {
            lock (this._syncRoot)
            {
                //this.RedisClient.HSet(mapName, GetBytes(key), GetBytes(value));
                this.RedisDatabase.HashSet(mapName, key, value);
            }
        }

        public string HGet(string mapName, string key)
        {
            lock (this._syncRoot)
            {
                //byte[] value = this.RedisClient.HGet(mapName, GetBytes(key));
                //if (value == null || value.Length == 0)
                //{
                //    return null;
                //}
                //string str = GetString(value);
                //return str;
                string str = this.RedisDatabase.HashGet(mapName, key);
                return str;
            }
        }

        public IDictionary<string, string> HGetAll(string mapName)
        {
            lock (this._syncRoot)
            {
                //byte[][] values = this.RedisClient.HGetAll(mapName);
                //int count = values.Length / 2;
                //IDictionary<string, string> dic = new Dictionary<string, string>(count);
                //for (int i = 0; i < values.Length;)
                //{
                //    string key = GetString(values[i++]);
                //    string value = GetString(values[i++]);
                //    dic[key] = value;
                //}

                //return dic;
                HashEntry[] entries = this.RedisDatabase.HashGetAll(mapName);
                IDictionary<string, string> dic = new Dictionary<string, string>();
                for (int i = 0; i < entries.Length; i++)
                {
                    HashEntry entry = entries[i];
                    string key = entry.Name;
                    string value = entry.Value;
                    dic[key] = value;
                }

                return dic;
            }
        }

        //private readonly Random _radom = new Random();

        public IDictionary<string, string> HScan(string mapName, string pattern, int size)
        {
            lock (this._syncRoot)
            {
                IEnumerable<HashEntry> entries = this.RedisDatabase.HashScan(
                    mapName, pattern, 10, CommandFlags.None);
                if (entries == null)
                {
                    throw new ApplicationException("HSCAN 命令出错,返回空");
                }
                IDictionary<string, string> dic = new Dictionary<string, string>();
                foreach (HashEntry entry in entries)
                {
                    string key = entry.Name;
                    string value = entry.Value;
                    dic[key] = value;
                    if (--size <= 0)
                    {
                        break;
                    }
                }

                return dic;
            }
        }

        public int Del(string key)
        {
            lock (this._syncRoot)
            {
                //int value = this.RedisClient.HDel(mapName, GetBytes(key));
                bool flag = this.RedisDatabase.KeyDelete(key);
                return flag ? 1 : 0;
            }
        }

        public void StringSet(string key, string value, TimeSpan? expiry = null)
        {
            lock (this._syncRoot)
            {
                //int value = this.RedisClient.HDel(mapName, GetBytes(key));
                this.RedisDatabase.StringSet(key, value, expiry);
                return;
            }
        }

        public string StringGet(string key)
        {
            lock (this._syncRoot)
            {
                //int value = this.RedisClient.HDel(mapName, GetBytes(key));
                RedisValue value = this.RedisDatabase.StringGet(key);
                string sv = (string)value;
                return sv;
            }
        }

        public int HDel(string mapName, string key)
        {
            lock (this._syncRoot)
            {
                //int value = this.RedisClient.HDel(mapName, GetBytes(key));
                bool flag = this.RedisDatabase.HashDelete(mapName, key);
                return flag ? 1 : 0;
            }
        }

        public void SAdd(string setName, string value)
        {
            lock (this._syncRoot)
            {
                bool flag = this.RedisDatabase.SetAdd(setName, value);
            }
        }

        public long SAdd(string setName, IList<string> values)
        {
            lock (this._syncRoot)
            {
                RedisValue[] rvs = values.Select(p => (RedisValue)p).ToArray();
                long count = this.RedisDatabase.SetAdd(setName, rvs);
                return count;
            }
        }

        public IList<string> SIntersect(IList<string> setNames)
        {
            lock (this._syncRoot)
            {
                RedisKey[] keys = setNames.Select(p => (RedisKey)(p)).ToArray();
                RedisValue[] values = this.RedisDatabase.SetCombine(SetOperation.Intersect, keys);
                IList<string> list = values.Select(p => (string)p).ToList();
                return list;
            }
        }

        public IList<string> SScan(string sname, string pattern, int offset, int count)
        {
            IList<string> list = new List<string>();
            lock (this._syncRoot)
            {
                IEnumerable<RedisValue> iter = this.RedisDatabase.SetScan(sname, pattern, 10);
                foreach (var item in iter)
                {
                    if (offset > 0)
                    {
                        --offset;
                        continue;
                    }
                    if (count > 0)
                    {
                        --count;
                        list.Add((string)item);
                    }
                }
            }
            return list;
        }

        public long SCard(string setName)
        {
            long result = this.RedisDatabase.SetLength(setName);
            return result;
        }

        public bool KeyExpire(string key, TimeSpan? ts)
        {
            lock (this._syncRoot)
            {
                bool flag = this.RedisDatabase.KeyExpire(key, ts);
                return flag;
            }
        }

        public bool KeyExists(string key)
        {
            lock (this._syncRoot)
            {
                bool flag = this.RedisDatabase.KeyExists(key);
                return flag;
            }
        }

        public string HGet(string assetsStatusMap)
        {
            throw new NotImplementedException();
        }

        //private string GetString(byte[] bytes)
        //{
        //    return _encoding.GetString(bytes);
        //}

        //private byte[] GetBytes(string str)
        //{
        //    return _encoding.GetBytes(str);
        //}

        public long LPush(string key, string value)
        {
            lock (this._syncRoot)
            {
                return this.RedisDatabase.ListLeftPush(key, value);
            }
        }

        public long RPush(string key, string value)
        {
            lock (this._syncRoot)
            {
                return this.RedisDatabase.ListRightPush(key, value);
            }
        }

        public string[] LRange(string key, long start, long stop)
        {
            lock (this._syncRoot)
            {
                var vals = this.RedisDatabase.ListRange(key, start, stop);
                return vals.Select(p => (string)p).ToArray();
            }
        }

        public void LRemove(string key, string value, int count)
        {
            lock (this._syncRoot)
            {
                this.RedisDatabase.ListRemove(key, value, count);
            }
        }
    }
}

具体调用详解

 class Program
    {
        static void Main(string[] args)
        {
            RedisHelper redis = null;
            redis = RedisHelper.Instance;
            string RedisServer = "127.0.0.1:6379";
            redis.Init(RedisServer);
            string KEY = "9526";
            if (!redis.KeyExists(KEY))
            {
                redis.HSet(KEY, "77", "55");
                redis.HSet(KEY, "77", "55");
                redis.HSet(KEY, "88", "66");
            }
            var a = redis.HGet(KEY, "77");
            var b = redis.Del(KEY);//返回1表示删除成功--根据redis键值删除
            var c = redis.HDel(KEY, "77"); //根据redis键值和存入数据的key删除指定的值
        }

    }

 存入

 根据redis的key与值中的key删除

02-09 22:03