VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之StackExchange.Redis 二次封装(4)

string result = value is string ? value.ToString() : 704 JsonConvert.SerializeObject(value, Formatting.None); 705 return result; 706 } 707 /// <summary> 708 /// 获取指定Key中最大Score值, 709 /// </summary> 710 /// <param name="key">key名称,注意要先添加上Key前缀</param> 711 /// <returns></returns> 712 private static double _GetScore(string key, IDatabase db) 713 { 714 double dValue = 0; 715 var rValue = db.SortedSetRangeByRankWithScores(key, 0, 0, Order.Descending).FirstOrDefault(); 716 dValue = rValue != null ? rValue.Score : 0; 717 return dValue + 1; 718 } 719 720 /// <summary> 721 /// 将值集合转换成RedisValue集合 722 /// </summary> 723 /// <typeparam name="T"></typeparam> 724 /// <param name="redisValues"></param> 725 /// <returns></returns> 726 private static RedisValue[] ConvertRedisValue<T>(params T[] redisValues) => redisValues.Select(o => (RedisValue)ConvertJson<T>(o)).ToArray(); 727 728 /// <summary> 729 /// 将值反系列化成对象集合 730 /// </summary> 731 /// <typeparam name="T"></typeparam> 732 /// <param name="values"></param> 733 /// <returns></returns> 734 public static List<T> ConvetList<T>(RedisValue[] values) 735 { 736 List<T> result = new List<T>(); 737 foreach (var item in values) 738 { 739 var model = ConvertObj<T>(item); 740 result.Add(model); 741 } 742 return result; 743 } 744 745 /// <summary> 746 /// 将值反系列化成对象 747 /// </summary> 748 /// <typeparam name="T"></typeparam> 749 /// <param name="value"></param> 750 /// <returns></returns> 751 public static T ConvertObj<T>(RedisValue value) 752 { 753 return value.IsNullOrEmpty ? default(T) : JsonConvert.DeserializeObject<T>(value); 754 } 755 756 /// <summary> 757 /// 获取几个集合的交叉并集合,并保存到一个新Key中 758 /// </summary> 759 /// <param name="db"></param> 760 /// <param name="operation">Union:并集 Intersect:交集 Difference:差集 详见 <see cref="SetOperation"/></param> 761 /// <param name="destination">保存的新Key名称</param> 762 /// <param name="keys">要操作的Key集合</param> 763 /// <returns></returns> 764 private static long _SortedSetCombineAndStore(IDatabase db, SetOperation operation, string destination, params string[] keys) 765 { 766 RedisKey[] keyList = ConvertRedisKeysAddSysCustomKey(keys); 767 var rValue = db.SortedSetCombineAndStore(operation, destination, keyList); 768 return rValue; 769 770 } 771 772 /// <summary> 773 /// 将string类型的Key转换成 <see cref="RedisKey"/> 型的Key,并添加前缀字符串 774 /// </summary> 775 /// <param name="redisKeys"></param> 776 /// <returns></returns> 777 private static RedisKey[] ConvertRedisKeysAddSysCustomKey(params string[] redisKeys) => redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray(); 778 #endregion 779 780 #endregion 781 782 #region 当作消息代理中间件使用 一般使用更专业的消息队列来处理这种业务场景 783 /// <summary> 784 /// 当作消息代理中间件使用 785 /// 消息组建中,重要的概念便是生产者,消费者,消息中间件。 786 /// </summary> 787 /// <param name="channel"></param> 788 /// <param name="message"></param> 789 /// <returns></returns> 790 public static long Publish(string channel, string message) 791 { 792 ISubscriber sub = Instance.GetSubscriber(); 793 //return sub.Publish("messages", "hello"); 794 return sub.Publish(channel, message); 795 } 796 797 /// <summary> 798 /// 在消费者端得到该消息并输出 799 /// </summary> 800 /// <param name="channelFrom"></param> 801 /// <returns></returns> 802 public static void Subscribe(string channelFrom) 803 { 804 ISubscriber sub = Instance.GetSubscriber(); 805 sub.Subscribe(channelFrom, (channel, message) => 806 { 807 Console.WriteLine((string)message); 808 }); 809 } 810 #endregion 811 812 #region EventHandler 813 /// <summary> 814 /// 连接失败 , 如果重新连接成功你将不会收到这个通知 815 /// </summary> 816 /// <param name="sender"></param> 817 /// <param name="e"></param> 818 private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e) 819 { 820 821 } 822 823 /// <summary> 824 /// 重新建立连接之前的错误 825 /// </summary> 826 /// <param name="sender"></param> 827 /// <param name="e"></param> 828 private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e) 829 { 830 831 } 832 833 /// <summary> 834 /// 发生错误时 835 /// </summary> 836 /// <param name="sender"></param> 837 /// <param name="e"></param> 838 private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e) 839 { 840 } 841 842 /// <summary> 843 /// 更改集群 844 /// </summary> 845 /// <param name="sender"></param> 846 /// <param name="e"></param> 847 private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e) 848 { 849 // LogHelper.WriteInfoLog("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint); 850 } 851 852 /// <summary> 853 /// redis类库错误 854 /// </summary> 855 /// <param name="sender"></param> 856 /// <param name="e"></param> 857 private static void MuxerInternalError(object sender, InternalErrorEventArgs e) 858 { 859 } 860 #endregion 861 } 862 }
复制代码

在以上RedisUtils帮助类的基础上封装一次调用:

复制代码
 /// <summary>
    /// Redis帮助类
    /// </summary>
    public class RedisHelper
    {
        /// <summary>
        /// 缓存失效时长
        /// </summary>
        public const int EXPIRY = 30;

        private static int CheckDbIndex(int dbIndex)
        {
            if (dbIndex > 16 || dbIndex < 0)
            {
                dbIndex = 0;
            }
            return dbIndex;
        }

        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbIndex">Redis数据库索引</param>
        /// <param name="key">Redis键</param>
        /// <param name="fun">从其他地方获取数据源,并缓存到Redis中</param>
        /// <param name="timeout">过期时间,单位:分钟</param>
        /// <returns></returns>
        public static T GetObject<T>(int dbIndex, string key, Func<T> fun, int? timeout = EXPIRY) where T : class
        {
            dbIndex = CheckDbIndex(dbIndex);
            T data = RedisUtils.StringGet<T>(dbIndex, key);
            if (data != null)
            {
                return data;
            }
            if (fun != null)
            {
                data = fun();
            }
            if (data != null)
            {
                TimeSpan? timeSp = null;
                if (timeout != null)
                    timeSp = TimeSpan.FromMinutes(Convert.ToDouble(timeout));
                RedisUtils.StringSet<T>(dbIndex, key, data, timeSp);
            }
            return data;
        }

        /// <summary>
        /// KV
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbIndex"></param>
        /// <param name="key"></param>
        /// <param name="func">如找不到则从func获取</param>
        /// <param name="timeout">超时时间</param>
        /// <returns></returns>
        public static T GetObject_KV<T>(int dbIndex, string key, Func<T> func, TimeSpan? timeout) where T : class
        {
            T data = RedisUtils.StringGet<T>(dbIndex, key);
            if (data != null)
            {
                return data;
            }
            if (func != null)
            {
                data = func();
            }
            if (data != null)
            {
                RedisUtils.StringSet<T>(dbIndex, key, data, timeout);
            }
            return data;
        }

        /// <summary>
        /// 异步获取缓存数据
        /// </summary>
        /// <typeparam name="T">数据集类型</typeparam>
        /// <param name="dbIndex">数据库</param>
        /// <param name="key"></param>
        /// <param name="fun">从其他地方获取数据源,并缓存到Redis中</param>
        /// <param name="timeout">过期时间,单位:分钟</param>
        /// <returns></returns>
        public static async Task<T> GetObjectAsync<T>(int dbIndex, string key, Func<T> fun, int timeout = EXPIRY) where T : class
        {
            dbIndex = CheckDbIndex(dbIndex);
            T data = RedisUtils.StringGet<T>(dbIndex, key);
            if (data != null)
            {
                return data;
            }

            if (fun != null)
            {
                data = await Task.Run(() =>
                {
                    return fun();
                });
            }
            if (data != null)
            {
                RedisUtils.StringSet<T>(dbIndex, key, data, TimeSpan.FromMinutes(timeout));
            }
            return data;
        }

        /// <summary>
        /// 异步获取缓存数据
        /// </summary>
        /// <typeparam name="T">数据集类型</typeparam>
        /// <param name="dbIndex">数据库</param>
        /// <param name="key"></param>
        /// <param name="fun">从其他地方获取数据源,并缓存到Redis中</param>
        /// <param name="timeout">过期时间,单位:分钟</param>
        /// <returns></returns>
        public static async Task<T> GetObjectAsync<T>(int dbIndex, string key, Func<RedisCache<T>> fun, int timeout = EXPIRY) where T : class
        {
            dbIndex = CheckDbIndex(dbIndex);
            RedisCache<T> cache = new RedisCache<T>();
            cache.CacheData = RedisUtils.StringGet<T>(dbIndex, key);
            if (cache.CacheData != null)
            {
                return cache.CacheData;
            }

            var temp = await Task.Run(() =>
            {
                return fun();
            });

            if (temp != null) cache = temp;

            if (cache.UseCache)
            {
                RedisUtils.StringSet<T>(dbIndex, key, cache.CacheData, TimeSpan.FromMinutes(timeout));
            }
            return cache.CacheData;
        }

        /// <summary>
        /// 异步获取数据集合
        /// </summary>
        /// <typeparam name="T">数据集类型</typeparam>
        /// <param name="dbIndex">数据库</param>
        /// <param name="key"></param>
        /// <param name="fun">从其他地方获取数据源,并缓存到Redis中</param>
        /// <param name="timeout">过期时间,单位:分钟</param>
        
      



  

相关教程
关于我们--广告服务--免责声明--本站帮助-友情链接--版权声明--联系我们       黑ICP备07002182号