using System.Collections.Generic; using System.Linq; namespace GSYWApi.Helper { /// /// redis数据库帮助类 /// public class DataHelper { #region 方法 -> 从Redis缓存中判断是否已存在数据 /// /// 从Redis缓存中判断是否已存在数据 /// /// 泛型对象 /// 表名称 /// 键值 /// redis数据库连接 /// public static bool ContainData(string tableName, string KeyValue, RedisHelper redisHelper) { //从Redis的db0数据库中获取信息 T InfoModel = redisHelper.HashGet(tableName, KeyValue); if (InfoModel != null) { return true; } return false; } #endregion #region 方法 -> 将数据记录Redis缓存中 /// /// 将数据记录Redis缓存中 /// /// 泛型对象 /// 保存到redis数据中的ObjectModel /// 数据表名称 /// 数据键值名称 /// 数据键值,若为空则取键值名称对应的值 /// redis数据库连接 /// 若存在相同的键值,是否要先删除再插入 /// public static bool RecordToRedis(T ObjectModel, string tableName, string KeyName, RedisHelper redisHelper, bool DeleteFlag = false, string KeyValue = "") { //获取item对象类型 var pros = typeof(T).GetProperties(); if (string.IsNullOrWhiteSpace(KeyValue)) { foreach (var item in pros) { if (item.Name == KeyName) { //获取字段对应的值,作为hash对象的唯一键值 KeyValue = item.GetValue(ObjectModel, null).ToString(); break; } } } //若要先删除再插入,则找到相同的键值数据进行删除 if (DeleteFlag && redisHelper.HashExists(tableName, KeyValue)) { redisHelper.HashDelete(tableName, KeyValue); } //写入Redis的数据库 return redisHelper.HashSet(tableName, KeyValue, ObjectModel); } /// /// 将数据记录Redis缓存中 /// /// 泛型对象 /// 保存到redis数据中的list数据集 /// 数据表名称 /// 数据键值 /// redis数据库连接 /// 若存在相同的键值,是否要先删除再插入 /// public static bool RecordToRedis(List listData, string tableName, string KeyName, RedisHelper redisHelper, bool DeleteFlag = false) { bool flag = false; foreach (T model in listData) { //写入Redis的数据库 flag = RecordToRedis(model, tableName, KeyName, redisHelper, DeleteFlag); } return flag; } #endregion #region 方法 -> 获取缓存数据集合List /// /// 获取缓存数据集合List /// /// 泛型对象 /// redis表名 /// redis数据库链接 /// public static List GetListData(string tableName, RedisHelper redisHelper) { //从缓存中获取营收趋势数据 List ListData = redisHelper.HashGetList(tableName).ToList(); return ListData; } #endregion } }