.Net使用Redis详解之ServiceStack.Redis

序言

 

本篇从.Net如何接入Reis开始,直至.Net对Redis的各种操作,为了方便学习与做为文档的查看,我做一遍注释展现,其中会对list的阻塞功能和事务的运用做二个案例,进行记录学习。

 

Redis官方推荐的.NET驱动类库为Service.Stack.Redis。然而网上对这个类库的中文文档不是很全面与合理,这篇文章主要就对这个类库做注释展现。不足遗漏之处还望见谅,海涵。

 

.Net使用Redis是非常方便与快捷与简单的,下面就让我展示下吧。

 

这里有必要说一下,如果你对Redis 中的基本对象数据类型还不了解,建议你看下我的前几篇Redis文章,保证要到病除。点击:我的Redis系列文章

 

 

项目中安装下载Service.Stack.Redis类库

 

右击项目->管理NuGet程序包->在联机中输入Reis就能出现这个类库,然后添加引入就行啦。

 

.Net链接Redis数据库,支持读写分离

1、配置文件

 

public sealed class RedisConfig : ConfigurationSection
    {
        public static RedisConfig GetConfig()
        {
            RedisConfig section = GetConfig("RedisConfig");
            return section;
        }

        public static RedisConfig GetConfig(string sectionName)
        {
            RedisConfig section = (RedisConfig)ConfigurationManager.GetSection(sectionName);
            if (section == null)
                throw new ConfigurationErrorsException("Section " + sectionName + " is not found.");
            return section;
        }
        /// <summary>
        /// 可写的Redis链接地址
        /// </summary>
        [ConfigurationProperty("WriteServerConStr", IsRequired = false)]
        public string WriteServerConStr
        {
            get
            {
                return (string)base["WriteServerConStr"];
            }
            set
            {
                base["WriteServerConStr"] = value;
            }
        }


        /// <summary>
        /// 可读的Redis链接地址
        /// </summary>
        [ConfigurationProperty("ReadServerConStr", IsRequired = false)]
        public string ReadServerConStr
        {
            get
            {
                return (string)base["ReadServerConStr"];
            }
            set
            {
                base["ReadServerConStr"] = value;
            }
        }
        /// <summary>
        /// 最大写链接数
        /// </summary>
        [ConfigurationProperty("MaxWritePoolSize", IsRequired = false, DefaultValue = 5)]
        public int MaxWritePoolSize
        {
            get
            {
                int _maxWritePoolSize = (int)base["MaxWritePoolSize"];
                return _maxWritePoolSize > 0 ? _maxWritePoolSize : 5;
            }
            set
            {
                base["MaxWritePoolSize"] = value;
            }
        }


        /// <summary>
        /// 最大读链接数
        /// </summary>
        [ConfigurationProperty("MaxReadPoolSize", IsRequired = false, DefaultValue = 5)]
        public int MaxReadPoolSize
        {
            get
            {
                int _maxReadPoolSize = (int)base["MaxReadPoolSize"];
                return _maxReadPoolSize > 0 ? _maxReadPoolSize : 5;
            }
            set
            {
                base["MaxReadPoolSize"] = value;
            }
        }


        /// <summary>
        /// 自动重启
        /// </summary>
        [ConfigurationProperty("AutoStart", IsRequired = false, DefaultValue = true)]
        public bool AutoStart
        {
            get
            {
                return (bool)base["AutoStart"];
            }
            set
            {
                base["AutoStart"] = value;
            }
        }



        /// <summary>
        /// 本地缓存到期时间,单位:秒
        /// </summary>
        [ConfigurationProperty("LocalCacheTime", IsRequired = false, DefaultValue = 36000)]
        public int LocalCacheTime
        {
            get
            {
                return (int)base["LocalCacheTime"];
            }
            set
            {
                base["LocalCacheTime"] = value;
            }
        }


        /// <summary>
        /// 是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项
        /// </summary>
        [ConfigurationProperty("RecordeLog", IsRequired = false, DefaultValue = false)]
        public bool RecordeLog
        {
            get
            {
                return (bool)base["RecordeLog"];
            }
            set
            {
                base["RecordeLog"] = value;
            }
        }

    }

 

2、配置Redis链接

 

public class RedisManager
    {
        /// <summary>
        /// redis配置文件信息
        /// </summary>
        private static RedisConfig RedisConfig = RedisConfig.GetConfig();

        private static PooledRedisClientManager prcm;

        /// <summary>
        /// 静态构造方法,初始化链接池管理对象
        /// </summary>
        static RedisManager()
        {
            CreateManager();
        }

        /// <summary>
        /// 创建链接池管理对象
        /// </summary>
        private static void CreateManager()
        {
            string[] WriteServerConStr = SplitString(RedisConfig.WriteServerConStr, ",");
            string[] ReadServerConStr = SplitString(RedisConfig.ReadServerConStr, ",");
            prcm = new PooledRedisClientManager(ReadServerConStr, WriteServerConStr,
                             new RedisClientManagerConfig
                             {
                                 MaxWritePoolSize = RedisConfig.MaxWritePoolSize,
                                 MaxReadPoolSize = RedisConfig.MaxReadPoolSize,
                                 AutoStart = RedisConfig.AutoStart,
                             });
        }

        private static string[] SplitString(string strSource, string split)
        {
            return strSource.Split(split.ToArray());
        }
        /// <summary>
        /// 客户端缓存操作对象
        /// </summary>
        public static IRedisClient GetClient()
        {
            if (prcm == null)
                CreateManager();
            return prcm.GetClient();
        }
    }

 

3、IRedisClient为操作Redis的接口,是.Net操作Redis的主要类库,这里我们把它接入

 

 /// <summary>
    /// RedisBase类,是redis操作的基类,继承自IDisposable接口,主要用于释放内存
    /// </summary>
    public abstract class RedisBase : IDisposable
    {
        public static IRedisClient Core { get; private set; }
        private bool _disposed = false;
        static RedisBase()
        {
            Core = RedisManager.GetClient();
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    Core.Dispose();
                    Core = null;
                }
            }
            this._disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        /// <summary>
        /// 保存数据DB文件到硬盘
        /// </summary>
        public void Save()
        {
            Core.Save();
        }
        /// <summary>
        /// 异步保存数据DB文件到硬盘
        /// </summary>
        public void SaveAsync()
        {
            Core.SaveAsync();
        }
    }

 

.Net操作Redis数据类型String

 

 

 

  public class DoRedisString : DoRedisBase
    {
        #region 赋值
        /// <summary>
        /// 设置key的value
        /// </summary>
        public bool Set(string key, string value)
        {
            return RedisBase.Core.Set<string>(key, value);
        }
        /// <summary>
        /// 设置key的value并设置过期时间
        /// </summary>
        public bool Set(string key, string value, DateTime dt)
        {
            return RedisBase.Core.Set<string>(key, value, dt);
        }
        /// <summary>
        /// 设置key的value并设置过期时间
        /// </summary>
        public bool Set(string key, string value, TimeSpan sp)
        {
            return RedisBase.Core.Set<string>(key, value, sp);
        }
        /// <summary>
        /// 设置多个key/value
        /// </summary>
        public void Set(Dictionary<string, string> dic)
        {
            RedisBase.Core.SetAll(dic);
        }

        #endregion
        #region 追加
        /// <summary>
        /// 在原有key的value值之后追加value
        /// </summary>
        public long Append(string key, string value)
        {
            return RedisBase.Core.AppendToValue(key, value);
        }
        #endregion
        #region 获取值
        /// <summary>
        /// 获取key的value值
        /// </summary>
        public string Get(string key)
        {
            return RedisBase.Core.GetValue(key);
        }
        /// <summary>
        /// 获取多个key的value值
        /// </summary>
        public List<string> Get(List<string> keys)
        {
            return RedisBase.Core.GetValues(keys);
        }
        /// <summary>
        /// 获取多个key的value值
        /// </summary>
        public List<T> Get<T>(List<string> keys)
        {
            return RedisBase.Core.GetValues<T>(keys);
        }
        #endregion
        #region 获取旧值赋上新值
        /// <summary>
        /// 获取旧值赋上新值
        /// </summary>
        public string GetAndSetValue(string key, string value)
        {
            return RedisBase.Core.GetAndSetValue(key, value);
        }
        #endregion
        #region 辅助方法
        /// <summary>
        /// 获取值的长度
        /// </summary>
        public long GetCount(string key)
        {
            return RedisBase.Core.GetStringCount(key);
        }
        /// <summary>
        /// 自增1,返回自增后的值
        /// </summary>
        public long Incr(string key)
        {
            return RedisBase.Core.IncrementValue(key);
        }
        /// <summary>
        /// 自增count,返回自增后的值
        /// </summary>
        public double IncrBy(string key, double count)
        {
            return RedisBase.Core.IncrementValueBy(key, count);
        }
        /// <summary>
        /// 自减1,返回自减后的值
        /// </summary>
        public long Decr(string key)
        {
            return RedisBase.Core.DecrementValue(key);
        }
        /// <summary>
        /// 自减count ,返回自减后的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public long DecrBy(string key, int count)
        {
            return RedisBase.Core.DecrementValueBy(key, count);
        }
        #endregion
    }

 

.Net操作Redis数据类型List

 

 

public class DoRedisList:DoRedisBase
    {
        #region 赋值
        /// <summary>
        /// 从左侧向list中添加值
        /// </summary>
        public void LPush(string key,string value)
        {
            RedisBase.Core.PushItemToList(key,value);
        }
        /// <summary>
        /// 从左侧向list中添加值,并设置过期时间
        /// </summary>
        public void LPush(string key, string value,DateTime dt)
        {
            RedisBase.Core.PushItemToList(key, value);
            RedisBase.Core.ExpireEntryAt(key,dt);
        }
        /// <summary>
        /// 从左侧向list中添加值,设置过期时间
        /// </summary>
        public void LPush(string key, string value, TimeSpan sp)
        {
            RedisBase.Core.PushItemToList(key, value);
            RedisBase.Core.ExpireEntryIn(key, sp);
        }
        /// <summary>
        /// 从左侧向list中添加值
        /// </summary>
        public void RPush(string key, string value)
        {
            RedisBase.Core.PrependItemToList(key,value);
        }
        /// <summary>
        /// 从右侧向list中添加值,并设置过期时间
        /// </summary>    
        public void RPush(string key, string value, DateTime dt)
        {
            RedisBase.Core.PrependItemToList(key, value);
            RedisBase.Core.ExpireEntryAt(key, dt);
        }
        /// <summary>
        /// 从右侧向list中添加值,并设置过期时间
        /// </summary>        
        public void RPush(string key, string value, TimeSpan sp)
        {
            RedisBase.Core.PrependItemToList(key, value);
            RedisBase.Core.ExpireEntryIn(key, sp);
        }
        /// <summary>
        /// 添加key/value
        /// </summary>     
        public void Add(string key, string value)
        {
            RedisBase.Core.AddItemToList(key,value);
        }
        /// <summary>
        /// 添加key/value ,并设置过期时间
        /// </summary>  
        public void Add(string key, string value,DateTime dt)
        {
            RedisBase.Core.AddItemToList(key, value);
            RedisBase.Core.ExpireEntryAt(key,dt);
        }
        /// <summary>
        /// 添加key/value。并添加过期时间
        /// </summary>  
        public void Add(string key, string value,TimeSpan sp)
        {
            RedisBase.Core.AddItemToList(key, value);
            RedisBase.Core.ExpireEntryIn(key,sp);
        }
        /// <summary>
        /// 为key添加多个值
        /// </summary>  
        public void Add(string key, List<string> values)
        {
            RedisBase.Core.AddRangeToList(key,values);
        }
        /// <summary>
        /// 为key添加多个值,并设置过期时间
        /// </summary>  
        public void Add(string key, List<string> values,DateTime dt)
        {
            RedisBase.Core.AddRangeToList(key, values);
            RedisBase.Core.ExpireEntryAt(key,dt);
        }
        /// <summary>
        /// 为key添加多个值,并设置过期时间
        /// </summary>  
        public void Add(string key, List<string> values,TimeSpan sp)
        {
            RedisBase.Core.AddRangeToList(key, values);
            RedisBase.Core.ExpireEntryIn(key,sp);
        }
        #endregion
        #region 获取值
        /// <summary>
        /// 获取list中key包含的数据数量
        /// </summary>  
        public long Count(string key)
        {
            return RedisBase.Core.GetListCount(key);
        }
        /// <summary>
        /// 获取key包含的所有数据集合
        /// </summary>  
        public List<string> Get(string key)
        {
            return RedisBase.Core.GetAllItemsFromList(key);
        }
        /// <summary>
        /// 获取key中下标为star到end的值集合
        /// </summary>  
        public List<string> Get(string key,int star,int end)
        {
            return RedisBase.Core.GetRangeFromList(key,star,end);
        }        
        #endregion
        #region 阻塞命令
        /// <summary>
        ///  阻塞命令:从list中keys的尾部移除一个值,并返回移除的值,阻塞时间为sp
        /// </summary>  
        public string BlockingPopItemFromList(string key,TimeSpan? sp)
        {
            return RedisBase.Core.BlockingDequeueItemFromList(key,sp);
        }
        /// <summary>
        ///  阻塞命令:从list中keys的尾部移除一个值,并返回移除的值,阻塞时间为sp
        /// </summary>  
        public ItemRef BlockingPopItemFromLists(string[] keys, TimeSpan? sp)
        {
            return RedisBase.Core.BlockingPopItemFromLists(keys, sp);
        }
        /// <summary>
        ///  阻塞命令:从list中keys的尾部移除一个值,并返回移除的值,阻塞时间为sp
        /// </summary>  
        public string BlockingDequeueItemFromList(string key, TimeSpan? sp)
        {
            return RedisBase.Core.BlockingDequeueItemFromList(key, sp);
        }
        /// <summary>
        /// 阻塞命令:从list中keys的尾部移除一个值,并返回移除的值,阻塞时间为sp
        /// </summary>  
        public ItemRef BlockingDequeueItemFromLists(string[] keys, TimeSpan? sp)
        {
            return RedisBase.Core.BlockingDequeueItemFromLists(keys, sp);
        }
        /// <summary>
        /// 阻塞命令:从list中key的头部移除一个值,并返回移除的值,阻塞时间为sp
        /// </summary>  
        public string BlockingRemoveStartFromList(string keys, TimeSpan? sp)
        {
            return RedisBase.Core.BlockingRemoveStartFromList(keys, sp);
        }
        /// <summary>
        /// 阻塞命令:从list中key的头部移除一个值,并返回移除的值,阻塞时间为sp
        /// </summary>  
        public ItemRef BlockingRemoveStartFromLists(string[] keys, TimeSpan? sp)
        {
            return RedisBase.Core.BlockingRemoveStartFromLists(keys, sp);
        }
        /// <summary>
        /// 阻塞命令:从list中一个fromkey的尾部移除一个值,添加到另外一个tokey的头部,并返回移除的值,阻塞时间为sp
        /// </summary>  
        public string BlockingPopAndPushItemBetweenLists(string fromkey, string tokey, TimeSpan? sp)
        {
            return RedisBase.Core.BlockingPopAndPushItemBetweenLists(fromkey, tokey, sp);
        }
        #endregion
        #region 删除
        /// <summary>
        /// 从尾部移除数据,返回移除的数据
        /// </summary>  
        public string PopItemFromList(string key)
        {
            return RedisBase.Core.PopItemFromList(key);
        }
        /// <summary>
        /// 移除list中,key/value,与参数相同的值,并返回移除的数量
        /// </summary>  
        public long RemoveItemFromList(string key,string value)
        {
            return RedisBase.Core.RemoveItemFromList(key,value);
        }
        /// <summary>
        /// 从list的尾部移除一个数据,返回移除的数据
        /// </summary>  
        public string RemoveEndFromList(string key)
        {
            return RedisBase.Core.RemoveEndFromList(key);
        }
        /// <summary>
        /// 从list的头部移除一个数据,返回移除的值
        /// </summary>  
        public string RemoveStartFromList(string key)
        {
            return RedisBase.Core.RemoveStartFromList(key);
        }       
        #endregion
        #region 其它
        /// <summary>
        /// 从一个list的尾部移除一个数据,添加到另外一个list的头部,并返回移动的值
        /// </summary>  
        public string PopAndPushItemBetweenLists(string fromKey, string toKey)
        {
            return RedisBase.Core.PopAndPushItemBetweenLists(fromKey,toKey);
        }
        #endregion
    }

 

展现List的阻塞功能,类似一个简单的消息队列功能

 

 

static void Main(string[] args)
        {
            string key = "zlh";
            //清空数据库
            DoRedisBase.Core.FlushAll();
            //给list赋值
            DoRedisBase.Core.PushItemToList(key, "1");
            DoRedisBase.Core.PushItemToList(key, "2");
            DoRedisBase.Core.AddItemToList(key, "3");
            DoRedisBase.Core.PrependItemToList(key, "0");
            DoRedisBase.Core.AddRangeToList(key, new List<string>() { "4", "5", "6" });
            #region 阻塞
            //启用一个线程来处理阻塞的数据集合
            new Thread(new ThreadStart(RunBlock)).Start();
            #endregion
            Console.ReadKey();
        }
        public static void RunBlock()
        {
            while (true)
            {               
               //如果key为zlh的list集合中有数据,则读出,如果没有则等待2个小时,2个小时中只要有数据进入这里就可以给打印出来,类似一个简易的消息队列功能。
               Console.WriteLine(DoRedisBase.Core.BlockingPopItemFromList("zlh", TimeSpan.FromHours(2)));
            }
        }

 

.Net操作Redis数据类型Set

 

 

 public class DoRedisSet:DoRedisBase
    {
        #region 添加
        /// <summary>
        /// key集合中添加value值
        /// </summary>
        public void Add(string key, string value)
        {
            RedisBase.Core.AddItemToSet(key,value);
        }
        /// <summary>
        /// key集合中添加list集合
        /// </summary>
        public void Add(string key, List<string> list)
        {
            RedisBase.Core.AddRangeToSet(key, list);
        }
        #endregion
        #region 获取
        /// <summary>
        /// 随机获取key集合中的一个值
        /// </summary>
        public string GetRandomItemFromSet(string key)
        {
           return RedisBase.Core.GetRandomItemFromSet(key);
        }
        /// <summary>
        /// 获取key集合值的数量
        /// </summary>
        public long GetCount(string key)
        {
            return RedisBase.Core.GetSetCount(key);
        }
        /// <summary>
        /// 获取所有key集合的值
        /// </summary>
        public HashSet<string> GetAllItemsFromSet(string key)
        {
            return RedisBase.Core.GetAllItemsFromSet(key);
        }
        #endregion
        #region 删除
        /// <summary>
        /// 随机删除key集合中的一个值
        /// </summary>
        public string PopItemFromSet(string key)
        {
            return RedisBase.Core.PopItemFromSet(key);
        }
        /// <summary>
        /// 删除key集合中的value
        /// </summary>
        public void RemoveItemFromSet(string key, string value)
        {
            RedisBase.Core.RemoveItemFromSet(key,value);
        }
        #endregion
        #region 其它
        /// <summary>
        /// 从fromkey集合中移除值为value的值,并把value添加到tokey集合中
        /// </summary>
        public void MoveBetweenSets(string fromkey,string tokey,string value)
        {
             RedisBase.Core.MoveBetweenSets(fromkey,tokey,value);
        }
        /// <summary>
        /// 返回keys多个集合中的并集,返还hashset
        /// </summary>
        public HashSet<string> GetUnionFromSets(string[] keys)
        {
           return RedisBase.Core.GetUnionFromSets(keys);
        }
        /// <summary>
        /// keys多个集合中的并集,放入newkey集合中
        /// </summary>
        public void StoreUnionFromSets(string newkey, string[] keys)
        {
             RedisBase.Core.StoreUnionFromSets(newkey,keys);
        }
        /// <summary>
        /// 把fromkey集合中的数据与keys集合中的数据对比,fromkey集合中不存在keys集合中,则把这些不存在的数据放入newkey集合中
        /// </summary>
        public void StoreDifferencesFromSet(string newkey, string fromkey, string[] keys)
        {
            RedisBase.Core.StoreDifferencesFromSet(newkey,fromkey,keys);
        }
        #endregion
    }

 

.Net操作Redis数据类型有序集合Zset

 

 

public class DoRedisZSet : DoRedisBase
    {
        #region 添加
        /// <summary>
        /// 添加key/value,默认分数是从1.多*10的9次方以此递增的,自带自增效果
        /// </summary>
        public bool AddItemToSortedSet(string key, string value)
        {
           return RedisBase.Core.AddItemToSortedSet(key, value);
        }
        /// <summary>
        /// 添加key/value,并设置value的分数
        /// </summary>
        public bool AddItemToSortedSet(string key, string value, double score)
        {
            return RedisBase.Core.AddItemToSortedSet(key, value, score);
        }
        /// <summary>
        /// 为key添加values集合,values集合中每个value的分数设置为score
        /// </summary>
        public bool AddRangeToSortedSet(string key,List<string> values,double score)
        {
            return RedisBase.Core.AddRangeToSortedSet(key, values, score);
        }
        /// <summary>
        /// 为key添加values集合,values集合中每个value的分数设置为score
        /// </summary>
        public bool AddRangeToSortedSet(string key, List<string> values, long score)
        {
            return RedisBase.Core.AddRangeToSortedSet(key, values, score);
        }
        #endregion
        #region 获取
        /// <summary>
        /// 获取key的所有集合
        /// </summary>
        public List<string> GetAllItemsFromSortedSet(string key)
        {
            return RedisBase.Core.GetAllItemsFromSortedSet(key);
        }
        /// <summary>
        /// 获取key的所有集合,倒叙输出
        /// </summary>
        public List<string> GetAllItemsFromSortedSetDesc(string key)
        {
            return RedisBase.Core.GetAllItemsFromSortedSetDesc(key);
        }
        /// <summary>
        /// 获取可以的说有集合,带分数
        /// </summary>
        public IDictionary<string, double> GetAllWithScoresFromSortedSet(string key)
        {
            return RedisBase.Core.GetAllWithScoresFromSortedSet(key);
        }
        /// <summary>
        /// 获取key为value的下标值
        /// </summary>
        public long GetItemIndexInSortedSet(string key, string value)
        {
            return RedisBase.Core.GetItemIndexInSortedSet(key, value);
        }
        /// <summary>
        /// 倒叙排列获取key为value的下标值
        /// </summary>
        public long GetItemIndexInSortedSetDesc(string key, string value)
        {
            return RedisBase.Core.GetItemIndexInSortedSetDesc(key, value);
        }
        /// <summary>
        /// 获取key为value的分数
        /// </summary>
        public double GetItemScoreInSortedSet(string key,string value)
        {
            return RedisBase.Core.GetItemScoreInSortedSet(key,value);
        }
        /// <summary>
        /// 获取key所有集合的数据总数
        /// </summary>
        public long GetSortedSetCount(string key)
        {
            return RedisBase.Core.GetSortedSetCount(key);
        }
        /// <summary>
        /// key集合数据从分数为fromscore到分数为toscore的数据总数
        /// </summary>
        public long GetSortedSetCount(string key,double fromScore,double toScore)
        {
            return RedisBase.Core.GetSortedSetCount(key,fromScore,toScore);
        }
        /// <summary>
        /// 获取key集合从高分到低分排序数据,分数从fromscore到分数为toscore的数据
        /// </summary>
        public List<string> GetRangeFromSortedSetByHighestScore(string key, double fromscore, double toscore)
        {
            return RedisBase.Core.GetRangeFromSortedSetByHighestScore(key, fromscore, toscore);
        }
        /// <summary>
        /// 获取key集合从低分到高分排序数据,分数从fromscore到分数为toscore的数据
        /// </summary>
        public List<string> GetRangeFromSortedSetByLowestScore(string key, double fromscore, double toscore)
        {
            return RedisBase.Core.GetRangeFromSortedSetByLowestScore(key, fromscore, toscore);
        }
        /// <summary>
        /// 获取key集合从高分到低分排序数据,分数从fromscore到分数为toscore的数据,带分数
        /// </summary>
        public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string key, double fromscore, double toscore)
        {
            return RedisBase.Core.GetRangeWithScoresFromSortedSetByHighestScore(key, fromscore, toscore);
        }
        /// <summary>
        ///  获取key集合从低分到高分排序数据,分数从fromscore到分数为toscore的数据,带分数
        /// </summary>
        public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string key, double fromscore, double toscore)
        {
            return RedisBase.Core.GetRangeWithScoresFromSortedSetByLowestScore(key, fromscore, toscore);
        }
        /// <summary>
        ///  获取key集合数据,下标从fromRank到分数为toRank的数据
        /// </summary>
        public List<string> GetRangeFromSortedSet(string key, int fromRank, int toRank)
        {
            return RedisBase.Core.GetRangeFromSortedSet(key, fromRank, toRank);
        }
        /// <summary>
        /// 获取key集合倒叙排列数据,下标从fromRank到分数为toRank的数据
        /// </summary>
        public List<string> GetRangeFromSortedSetDesc(string key, int fromRank, int toRank)
        {
            return RedisBase.Core.GetRangeFromSortedSetDesc(key, fromRank, toRank);
        }
        /// <summary>
        /// 获取key集合数据,下标从fromRank到分数为toRank的数据,带分数
        /// </summary>
        public IDictionary<string, double> GetRangeWithScoresFromSortedSet(string key, int fromRank, int toRank)
        {
            return RedisBase.Core.GetRangeWithScoresFromSortedSet(key, fromRank, toRank);
        }
        /// <summary>
        ///  获取key集合倒叙排列数据,下标从fromRank到分数为toRank的数据,带分数
        /// </summary>
        public IDictionary<string, double> GetRangeWithScoresFromSortedSetDesc(string key, int fromRank, int toRank)
        {
            return RedisBase.Core.GetRangeWithScoresFromSortedSetDesc(key, fromRank, toRank);
        }
        #endregion
        #region 删除
        /// <summary>
        /// 删除key为value的数据
        /// </summary>
        public bool RemoveItemFromSortedSet(string key,string value)
        {
            return RedisBase.Core.RemoveItemFromSortedSet(key, value);
        }
        /// <summary>
        /// 删除下标从minRank到maxRank的key集合数据
        /// </summary>
        public long RemoveRangeFromSortedSet(string key,int minRank,int maxRank)
        {
            return RedisBase.Core.RemoveRangeFromSortedSet(key,minRank,maxRank);
        }
        /// <summary>
        /// 删除分数从fromscore到toscore的key集合数据
        /// </summary>
        public long RemoveRangeFromSortedSetByScore(string key, double fromscore, double toscore)
        {
            return RedisBase.Core.RemoveRangeFromSortedSetByScore(key, fromscore, toscore);
        }
        /// <summary>
        /// 删除key集合中分数最大的数据
        /// </summary>
        public string PopItemWithHighestScoreFromSortedSet(string key)
        {
            return RedisBase.Core.PopItemWithHighestScoreFromSortedSet(key);
        }
        /// <summary>
        /// 删除key集合中分数最小的数据
        /// </summary>
        public string PopItemWithLowestScoreFromSortedSet(string key)
        {
            return RedisBase.Core.PopItemWithLowestScoreFromSortedSet(key);
        }
        #endregion
        #region 其它
        /// <summary>
        /// 判断key集合中是否存在value数据
        /// </summary>
        public bool SortedSetContainsItem(string key, string value)
        {
            return RedisBase.Core.SortedSetContainsItem(key,value);
        }
        /// <summary>
        /// 为key集合值为value的数据,分数加scoreby,返回相加后的分数
        /// </summary>
        public double IncrementItemInSortedSet(string key,string value,double scoreBy)
        {
            return RedisBase.Core.IncrementItemInSortedSet(key,value,scoreBy);
        }
        /// <summary>
        /// 获取keys多个集合的交集,并把交集添加的newkey集合中,返回交集数据的总数
        /// </summary>
        public long StoreIntersectFromSortedSets(string newkey, string[] keys)
        {
            return RedisBase.Core.StoreIntersectFromSortedSets(newkey,keys);
        }
        /// <summary>
        /// 获取keys多个集合的并集,并把并集数据添加到newkey集合中,返回并集数据的总数
        /// </summary>
        public long StoreUnionFromSortedSets(string newkey, string[] keys)
        {
            return RedisBase.Core.StoreUnionFromSortedSets(newkey, keys);
        }
        #endregion
    }

 

.Net操作Redis数据类型哈希Hash

 

 

 public class DoRedisHash :DoRedisBase
    {
        #region 添加
        /// <summary>
        /// 向hashid集合中添加key/value
        /// </summary>       
        public bool SetEntryInHash(string hashid, string key, string value)
        {
            return RedisBase.Core.SetEntryInHash(hashid,key,value);
        }
        /// <summary>
        /// 如果hashid集合中存在key/value则不添加返回false,如果不存在在添加key/value,返回true
        /// </summary>
        public bool SetEntryInHashIfNotExists(string hashid, string key, string value)
        {
            return RedisBase.Core.SetEntryInHashIfNotExists(hashid, key, value);
        }
        /// <summary>
        /// 存储对象T t到hash集合中
        /// </summary>
        public void StoreAsHash<T>(T t)
        {
            RedisBase.Core.StoreAsHash<T>(t);
        }
        #endregion
        #region 获取
        /// <summary>
        /// 获取对象T中ID为id的数据。
        /// </summary>
        public T GetFromHash<T>(object id)
        {
            return RedisBase.Core.GetFromHash<T>(id);
        }
        /// <summary>
        /// 获取所有hashid数据集的key/value数据集合
        /// </summary>
        public Dictionary<string, string> GetAllEntriesFromHash(string hashid)
        {
            return RedisBase.Core.GetAllEntriesFromHash(hashid);
        }
        /// <summary>
        /// 获取hashid数据集中的数据总数
        /// </summary>
        public long GetHashCount(string hashid)
        {
            return RedisBase.Core.GetHashCount(hashid);
        }
        /// <summary>
        /// 获取hashid数据集中所有key的集合
        /// </summary>
        public List<string> GetHashKeys(string hashid)
        {
            return RedisBase.Core.GetHashKeys(hashid);
        }
        /// <summary>
        /// 获取hashid数据集中的所有value集合
        /// </summary>
        public List<string> GetHashValues(string hashid)
        {
            return RedisBase.Core.GetHashValues(hashid);
        }
        /// <summary>
        /// 获取hashid数据集中,key的value数据
        /// </summary>
        public string GetValueFromHash(string hashid, string key)
        {
            return RedisBase.Core.GetValueFromHash(hashid, key);
        }
        /// <summary>
        /// 获取hashid数据集中,多个keys的value集合
        /// </summary>
        public List<string> GetValuesFromHash(string hashid, string[] keys)
        {
            return RedisBase.Core.GetValuesFromHash(hashid, keys);
        }
        #endregion
        #region 删除
        #endregion
        /// <summary>
        /// 删除hashid数据集中的key数据
        /// </summary>
        public bool RemoveEntryFromHash(string hashid, string key)
        {
            return RedisBase.Core.RemoveEntryFromHash(hashid, key);
        }     
        #region 其它
        /// <summary>
        /// 判断hashid数据集中是否存在key的数据
        /// </summary>
        public bool HashContainsEntry(string hashid, string key)
        {
            return RedisBase.Core.HashContainsEntry(hashid,key);
        }
        /// <summary>
        /// 给hashid数据集key的value加countby,返回相加后的数据
        /// </summary>
        public double IncrementValueInHash(string hashid, string key, double countBy)
        {
            return RedisBase.Core.IncrementValueInHash(hashid, key, countBy);
        }
        #endregion
    }

 

.Net操作Redis中的事务与锁

 

 

static void Main(string[] args)
        {
            //清空数据库
            DoRedisBase.Core.FlushAll();
            //声明事务
            using (var tran = RedisManager.GetClient().CreateTransaction())
            {
                try
                {
                    tran.QueueCommand(p =>
                    {
                        //操作redis数据命令
                        DoRedisBase.Core.Set<int>("name", 30);
                        long i = DoRedisBase.Core.IncrementValueBy("name", 1);
                    });
                    //提交事务
                    tran.Commit();
                }
                catch
                {
                    //回滚事务
                    tran.Rollback();
                }
                ////操作redis数据命令
                //RedisManager.GetClient().Set<int>("zlh", 30);
                ////声明锁,网页程序可获得锁效果
                //using (RedisManager.GetClient().AcquireLock("zlh"))
                //{
                //    RedisManager.GetClient().Set<int>("zlh", 31);
                //    Thread.Sleep(10000);
                //}
            }
            Console.ReadKey();
        }

 

 

 

ServiceStack.Redis文档观看

posted on 2016-05-04 14:22  邬兴亮  阅读(4156)  评论(1编辑  收藏  举报

导航