c#--Redis帮助类
最近一直在忙公司的一下项目,也没有太多时间写,所以就分享出所用redis帮助类
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using ZsqApp.Core.Infrastructure.Extentions;
using ZsqApp.Core.Infrastructure.SysEnum; namespace ZsqApp.Core.Infrastructure.Utilities
{
//**************操作记录******************
//内容描述:Redis帮助类
//***************************************
public static class RedisHelper
{ private static string _strConn = "地址";
private static string _strPwd = "密码"; private static int _strDb = -1;
static ConnectionMultiplexer _redis;
static readonly object _locker = new object(); #region 单例模式
public static ConnectionMultiplexer Manager
{ get
{
if (_redis == null)
{
lock (_locker)
{
if (_redis != null) return _redis;
_redis = GetManager();
return _redis;
}
}
return _redis;
}
} private static ConnectionMultiplexer GetManager(string connectionString = null)
{ if (StringExtension.IsBlank(connectionString))
{
connectionString = _strConn;
}
var options = ConfigurationOptions.Parse(connectionString);
options.Password = _strPwd;
return ConnectionMultiplexer.Connect(options);
}
#endregion #region 辅助方法
/// <summary>
/// 对象序列化成字符串
/// </summary>
/// <typeparam name="T">泛型对象</typeparam>
/// <param name="value"></param>
/// <returns></returns>
private static string ConvertJson<T>(T value)
{
string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
return result;
} /// <summary>
/// RedisValue序列化成对象
/// </summary>
/// <typeparam name="T">序列化后的对象</typeparam>
/// <param name="value">RedisValue</param>
/// <returns></returns>
private static T ConvertObj<T>(RedisValue value)
{
if (StringExtension.IsBlank(value))
{
return default(T);
}
else
{
return JsonConvert.DeserializeObject<T>(value);
}
} /// <summary>
/// 多个值序列化成list集合
/// </summary>
/// <typeparam name="T">集合对象</typeparam>
/// <param name="values">RedisValue</param>
/// <returns></returns>
private static List<T> ConvetList<T>(RedisValue[] values)
{
List<T> result = new List<T>();
foreach (var item in values)
{
var model = ConvertObj<T>(item);
if (model != null)
result.Add(model);
}
return result;
} private static RedisKey[] ConvertRedisKeys(List<string> redisKeys, string prefix)
{
if (StringExtension.IsBlank(prefix))
{
return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
}
else
{
return redisKeys.Select(redisKey => (RedisKey)(prefix + ":" + redisKey)).ToArray();
}
} /// <summary>
/// 获取要操作的库
/// </summary>
/// <param name="db">库,0和-1都是第一个库,1是第二个库...</param>
/// <returns></returns>
private static int GetOperationDB(RedisEnum db)
{
if (db == RedisEnum.Default)
{
return _strDb;
}
else
{
return (int)db;
}
} /// <summary>
/// 获得枚举的Description
/// </summary>
/// <param name="value">枚举值</param>
/// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
/// <returns>枚举的Description</returns>
private static string GetDescription(this Enum value, Boolean nameInstead = true)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name == null)
{
return null;
} FieldInfo field = type.GetField(name);
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute == null && nameInstead == true)
{
return name;
}
return attribute == null ? null : attribute.Description;
}
#endregion /// <summary>
/// 是否存在
/// </summary>
/// <param name="key">键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
public static bool KeyExists(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
try
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).KeyExists(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key);
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 设置过期时间
/// </summary>
/// <param name="key">键</param>
/// <param name="min">过期时间,单位:分钟</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
public static bool KeyExpire(string key, int min = 600, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
try
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).KeyExpire(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, DateTime.Now.AddMinutes(min));
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 修改键
/// </summary>
/// <param name="key">键</param>
/// <param name="newKey">新键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool KeyRename(string key, string newKey, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
try
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).KeyRename(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, StringExtension.IsBlank(strFd) ? newKey : strFd + ":" + newKey);
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 清空
/// </summary>
/// <param name="key">键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static IEnumerable<RedisKey> AllClear(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
return Manager.GetServer(_strConn, _strPwd).Keys(GetOperationDB(db), key);
} /// <summary>
/// 删除
/// </summary>
/// <param name="key">键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool KeyDelete(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
try
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).KeyDelete(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key);
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 批量删除
/// </summary>
/// <param name="keys">键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long KeyDelete(List<string> keys, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
try
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).KeyDelete(ConvertRedisKeys(keys, strFd));
}
catch (Exception)
{
return 0;
}
} /// <summary>
/// 缓存单个字符串
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="expireMinutes">过期时间,单位:分钟</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool StringSet(string key, string value, int expireMinutes = 600, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).StringSet(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, value, TimeSpan.FromMinutes(expireMinutes));
} /// <summary>
/// 批量缓存字符串
/// </summary>
/// <param name="keysStr">键</param>
/// <param name="valuesStr">值</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool StringSet(string[] keysStr, string[] valuesStr, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
var vCount = keysStr.Length;
var vKeyValuePair = new KeyValuePair<RedisKey, RedisValue>[vCount];
for (int i = 0; i < vCount; i++)
{
vKeyValuePair[i] = new KeyValuePair<RedisKey, RedisValue>(StringExtension.IsBlank(strFd) ? keysStr[i] : strFd + ":" + keysStr[i], valuesStr[i]);
}
return Manager.GetDatabase(GetOperationDB(db)).StringSet(vKeyValuePair);
} /// <summary>
/// 缓存限时对象
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="obj">值</param>
/// <param name="expireMinutes">过期时间,单位:分钟</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool StringSet<T>(string key, T obj, int expireMinutes = 600, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).StringSet(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, JsonHelper.SerializeObject(obj), TimeSpan.FromMinutes(expireMinutes));
} /// <summary>
/// 缓存对象
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="obj">值</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool StringSet<T>(string key, T obj, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).StringSet(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, JsonHelper.SerializeObject(obj));
} /// <summary>
/// 根据key获取值
/// </summary>
/// <param name="key">键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static string StringGet(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).StringGet(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key);
} /// <summary>
/// 批量根据key获取
/// </summary>
/// <param name="keys">键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static RedisValue[] StringGet(List<string> keys, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).StringGet(ConvertRedisKeys(keys, strFd));
} /// <summary>
/// 根据key获取单个对象
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static T StringGet<T>(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
string vValue = Manager.GetDatabase(GetOperationDB(db)).StringGet(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key);
return ConvertObj<T>(vValue);
} /// <summary>
/// 入栈(后插入的在List前面)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
public static long ListLeftPush<T>(string key, T value, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).ListLeftPush(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, ConvertJson(value));
} /// <summary>
/// 批量入栈(后插入的在List前面)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="values">值</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long ListLeftPush<T>(string key, List<T> values, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
var vRedisValues = values.Select(m => (RedisValue)ConvertJson(m)).ToArray();
return Manager.GetDatabase(GetOperationDB(db)).ListLeftPush(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, vRedisValues);
} /// <summary>
/// 出栈(删除最前面的一个元素并返回)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static T ListLeftPop<T>(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
var vRedisValues = Manager.GetDatabase(GetOperationDB(db)).ListLeftPop(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key);
return ConvertObj<T>(vRedisValues);
} /// <summary>
/// 入队(后插入的在List后面)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
public static long ListRightPush<T>(string key, T value, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).ListRightPush(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, ConvertJson(value));
} /// <summary>
/// 批量入队(后插入的在List后面)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="values">值</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long ListRightPush<T>(string key, List<T> values, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
var vRedisValues = values.Select(m => (RedisValue)ConvertJson(m)).ToArray();
return Manager.GetDatabase(GetOperationDB(db)).ListRightPush(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, vRedisValues);
} /// <summary>
/// 获取
/// <typeparam name="T">类型</typeparam>
/// <param name="key">键</param>
/// <param name="start">索引开始</param>
/// <param name="stop">索引结束</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static List<T> ListRange<T>(string key, long start = 0, long stop = -1, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
var vRedisValues = Manager.GetDatabase(GetOperationDB(db)).ListRange(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key, start, stop);
return ConvetList<T>(vRedisValues);
} /// <summary>
/// 获取个数
/// </summary>
/// <param name="key">键</param>
/// <param name="folder">目录,默认根目录</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long ListLength(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.Default)
{
string strFd = GetDescription(folder);
return Manager.GetDatabase(GetOperationDB(db)).ListLength(StringExtension.IsBlank(strFd) ? key : strFd + ":" + key);
} }
}
c#--Redis帮助类的更多相关文章
- StackExchange.Redis帮助类解决方案RedisRepository封装(基础配置)
本文版权归博客园和作者吴双本人共同所有,转载和爬虫,请注明原文地址.http://www.cnblogs.com/tdws/p/5815735.html 写在前面 这不是教程,分享而已,也欢迎园友们多 ...
- php的redis 操作类,适用于单台或多台、多组redis服务器操作
redis 操作类,包括单台或多台.多组redis服务器操作,适用于业务复杂.高性能要求的 php web 应用. redis.php: <?php /* redis 操作类,适用于单台或多台. ...
- Redis操作Hash工具类封装,Redis工具类封装
Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...
- Redis操作字符串工具类封装,Redis工具类封装
Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...
- 自己封装的C#操作redis公共类
关于C#操作redis公共类,网上有很多版本,每个版本我都看了,发觉还是不够完美,都存在一个问题,只能操作单一的缓存数据库 redis指令支持上,这里可以自己去扩展,下面分享下我近期封装的一个redi ...
- 设计模式之PHP项目应用——单例模式设计Memcache和Redis操作类
1 单例模式简单介绍 单例模式是一种经常使用的软件设计模式. 在它的核心结构中仅仅包括一个被称为单例类的特殊类. 通过单例模式能够保证系统中一个类仅仅有一个实例并且该实例易于外界訪问.从而方便对实例个 ...
- redis 工具类 单个redis、JedisPool 及多个redis、shardedJedisPool与spring的集成配置
http://www.cnblogs.com/edisonfeng/p/3571870.html http://javacrazyer.iteye.com/blog/1840161 http://ww ...
- .net core下Redis帮助类
0.引入.net core环境下Redis的NuGet包,StackExchange.Redis,现目前最新的2.0.519. 帮助类Code: using System; using Syste ...
- SpringBoot整合Redis及Redis工具类撰写
SpringBoot整合Redis的博客很多,但是很多都不是我想要的结果.因为我只需要整合完成后,可以操作Redis就可以了,并不需要配合缓存相关的注解使用(如@Cacheable). ...
随机推荐
- JSON 的几种转换
package com.qbskj.project.util; import java.io.IOException; import java.io.Writer; import org.spring ...
- PHP九大接口视频教程( 支付宝,QQ,短信接口,微信接口开发, 支付宝即时到账接口开发三级分销全套)
PHP九大接口视频教程( 支付宝,QQ,短信接口,微信接口开发, 支付宝即时到账接口开发三级分销全套) 需要的联系我:QQ: 1844912514 PHP九大接口视频教程( 支付宝,QQ,短信接口 ...
- Pyhon进阶9---类的继承
类的继承 基本概念 定义 格式如下 继承中的访问控制 class Animal: __CNOUT = 0 HEIGHT = 0 def __init__(self,age,weight,height) ...
- linux下JNI开发—Hello为例
转自:https://www.cnblogs.com/snake-hand/archive/2012/05/25/2517412.html 前期准备: 1.Java JDK 2.gcc 3.g++ 确 ...
- iOS presentViewController 方法引起的问题
有个需求,在项目中随时使用 presentViewController来显示一个界面,比如弹窗提示或者人脸解锁,都是在任何情况都可能出现的. 在presentViewController 调用前,已经 ...
- Go语言里的slice
1.切片是基于数组做的一层封装,灵活能够自动扩容. 2.切片的初始化方法 ①直接创建 ②基于已有的数组或切片 ③使用make来创建一个切片 第一个5是切片的大小 第二个5是切片的容量 3.基本操作 ① ...
- ECMA262,JavaScript引擎,浏览器
相关阅读:https://www.cnblogs.com/970119449blog/p/8080133.html 相关阅读:https://www.jb51.net/article/75888.ht ...
- 【dp】合唱队形
题目描述 NN位同学站成一排,音乐老师要请其中的(N-KN−K)位同学出列,使得剩下的KK位同学排成合唱队形. 合唱队形是指这样的一种队形:设K位同学从左到右依次编号为1,2,…,K,他们的身高分别为 ...
- PyCharm的安装和应用
一.前言 大约几年以前,我曾经跟别人吹过牛逼,说我会深度学习.吹牛的后果就是我得逼自己把深度学习放在我的to-do-list里,在别人揭发我吹牛之前把深度学习学会了,才能名正言顺得对外宣称,我并没有吹 ...
- (贪心 字符串 打好基础)51nod 1182完美字符串
约翰认为字符串的完美度等于它里面所有字母的完美度之和.每个字母的完美度可以由你来分配,不同字母的完美度不同,分别对应一个1-26之间的整数. 约翰不在乎字母大小写(也就是说字母A和a的完美度相同).给 ...