当前位置:
首页 > 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>
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式