RedisHelper (C#)
<add key="RedisServers" value="172.20.2.90:9379,password=Aa+123456789" />
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq; namespace APP.Common
{
/// <summary>
/// StackExchangeRedis帮助类
/// </summary>
public sealed class RedisHelper
{
/// <summary>
/// Redis服务器地址
/// </summary>
private static readonly string ConnectionString = System.Configuration.ConfigurationManager.AppSettings["RedisServers"]; /// <summary>
/// 静态变量锁
/// </summary>
private static object _locker = new Object(); /// <summary>
/// 静态实例
/// </summary>
private static ConnectionMultiplexer _instance = null; /// <summary>
/// 使用一个静态属性来返回已连接的实例,如下列中所示。这样,一旦 ConnectionMultiplexer 断开连接,便可以初始化新的连接实例。
/// </summary>
private static ConnectionMultiplexer Instance
{
get
{
try
{
if (_instance == null)
{
lock (_locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = ConnectionMultiplexer.Connect(ConnectionString);
//注册如下事件
_instance.ConnectionFailed += MuxerConnectionFailed;
_instance.ConnectionRestored += MuxerConnectionRestored;
_instance.ErrorMessage += MuxerErrorMessage;
_instance.ConfigurationChanged += MuxerConfigurationChanged;
_instance.HashSlotMoved += MuxerHashSlotMoved;
_instance.InternalError += MuxerInternalError;
}
}
} }
catch (Exception ex)
{
LogHelper.Error(typeof(RedisHelper), string.Format("redis初始化异常,连接字符串={0}", ConnectionString), ex);
}
return _instance;
}
} /// <summary>
/// 获取redis数据库对象
/// </summary>
/// <returns></returns>
private static IDatabase GetDatabase()
{
return Instance.GetDatabase();
} /// <summary>
/// 检查Key是否存在
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Exists(string key)
{
if (string.IsNullOrWhiteSpace(key))
{
return false;
}
try
{
return GetDatabase().KeyExists(key);
}
catch (Exception ex)
{
LogHelper.Error(typeof(RedisHelper), string.Format("检查Key是否存在异常,缓存key={0}", key), ex);
}
return false;
} /// <summary>
/// 设置String类型的缓存对象(如果value是null或者空字符串则设置失败)
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="ts">过期时间</param>
public static bool SetString(string key, string value, TimeSpan? ts = null)
{
if (string.IsNullOrWhiteSpace(value))
{
return false;
}
try
{
return GetDatabase().StringSet(key, value, ts);
}
catch (Exception ex)
{
LogHelper.Error(typeof(RedisHelper), string.Format("设置string类型缓存异常,缓存key={0},缓存值={1}", key, value), ex);
}
return false;
} /// <summary>
/// 根据key获取String类型的缓存对象
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetString(string key)
{
try
{
return GetDatabase().StringGet(key);
}
catch (Exception ex)
{
LogHelper.Error(typeof(RedisHelper), string.Format("获取string类型缓存异常,缓存key={0}", key), ex);
}
return null;
} /// <summary>
/// 删除缓存
/// </summary>
/// <param name="key">key</param>
/// <returns></returns>
public static bool KeyDelete(string key)
{
try
{
return GetDatabase().KeyDelete(key);
}
catch (Exception ex)
{
LogHelper.Error(typeof(RedisHelper), "删除缓存异常,缓存key={0}" + key, ex);
return false;
}
}
/// <summary>
/// 设置Hash类型缓存对象(如果value没有公共属性则不设置缓存)
/// 会使用反射将object对象所有公共属性作为Hash列存储
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public static void SetHash(string key, object value)
{
if (null == value)
{
return;
}
try
{
List<HashEntry> list = new List<HashEntry>();
Type type = value.GetType();
var propertyArray = type.GetProperties();
foreach (var property in propertyArray)
{
string propertyName = property.Name;
string propertyValue = property.GetValue(value).ToString();
list.Add(new HashEntry(propertyName, propertyValue));
}
if (list.Count < )
{
return;
}
IDatabase db = GetDatabase();
db.HashSet(key, list.ToArray());
}
catch (Exception ex)
{
LogHelper.Error(typeof(RedisHelper), string.Format("设置Hash类型缓存异常,缓存key={0},缓存值={1}", key, Utils.SerializeObject(value)), ex);
}
} /// <summary>
/// 设置Hash类型缓存对象(用于存储对象)
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">字典,key是列名 value是列的值</param>
public static void SetHash(string key, Dictionary<string, string> value)
{
if (null == value || value.Count < )
{
return;
}
try
{
HashEntry[] array = (from item in value select new HashEntry(item.Key, item.Value)).ToArray();
IDatabase db = GetDatabase();
db.HashSet(key, array);
}
catch (Exception ex)
{
LogHelper.Error(typeof(RedisHelper), string.Format("设置Hash类型缓存异常,缓存key={0},缓存对象值={1}", key, string.Join(",", value)), ex);
}
} /// <summary>
/// 根据key和列数组从缓存中拿取数据(如果fieldList为空或者个数小于0返回null)
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="fieldList">列数组</param>
/// <returns>根据列数组构造一个字典,字典中的列与入参列数组相同,字典中的值是每一列的值</returns>
public static Dictionary<string, string> GetHash(string key, List<string> fieldList)
{
if (null == fieldList || fieldList.Count < )
{
return null;
}
try
{
Dictionary<string, string> dic = new Dictionary<string, string>();
RedisValue[] array = (from item in fieldList select (RedisValue)item).ToArray();
IDatabase db = GetDatabase();
RedisValue[] redisValueArray = db.HashGet(key, array);
for (int i = ; i < redisValueArray.Length; i++)
{
string field = fieldList[i];
string value = redisValueArray[i];
dic.Add(field, value);
}
return dic;
}
catch (Exception ex)
{
LogHelper.Error(typeof(RedisHelper), string.Format("获取Hash类型缓存异常,缓存key={0},列数组={1}", key, string.Join(",", fieldList)), ex);
}
return null;
} /// <summary>
/// 使用Redis incr 记录某个Key的调用次数
/// </summary>
/// <param name="key"></param>
public static long SaveInvokeCount(string key)
{
try
{
return GetDatabase().StringIncrement(key);
}
catch { return -; }
} /// <summary>
/// 配置更改时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
LogHelper.Warn(typeof(RedisHelper), "MuxerConfigurationChanged=>e.EndPoint=" + e.EndPoint, null);
} /// <summary>
/// 发生错误时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
LogHelper.Error(typeof(RedisHelper), "MuxerErrorMessage=>e.EndPoint=" + e.EndPoint + ",e.Message=" + e.Message, null);
} /// <summary>
/// 重新建立连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
LogHelper.Warn(typeof(RedisHelper), "MuxerConnectionRestored=>e.ConnectionType=" + e.ConnectionType + ",e.EndPoint=" + e.EndPoint + ",e.FailureType=" + e.FailureType, e.Exception);
} /// <summary>
/// 连接失败
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
LogHelper.Error(typeof(RedisHelper), "MuxerConnectionFailed=>e.ConnectionType=" + e.ConnectionType + ",e.EndPoint=" + e.EndPoint + ",e.FailureType=" + e.FailureType, e.Exception);
} /// <summary>
/// 更改集群
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
LogHelper.Warn(typeof(RedisHelper), "MuxerHashSlotMoved=>" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint, null);
} /// <summary>
/// redis类库错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
LogHelper.Error(typeof(RedisHelper), "MuxerInternalError", e.Exception);
}
}
}
//写String 缓存1小时
RedisHelper.SetString(subID, "AXB", new TimeSpan(, , , )); //写String 缓存5分钟
RedisHelper.SetString(mobile + "_car", equipmentType, TimeSpan.FromMinutes()); //写String
RedisHelper.SetString(strNum, strCity); //读String
string strTime = RedisHelper.GetString(mobile);
RedisHelper (C#)的更多相关文章
- Basic Tutorials of Redis(9) -First Edition RedisHelper
After learning the basic opreation of Redis,we should take some time to summarize the usage. And I w ...
- C# Azure 存储-分布式缓存Redis工具类 RedisHelper
using System; using System.Collections.Generic; using Newtonsoft.Json; using StackExchange.Redis; na ...
- Asp.Net Core 2.0 项目实战(6)Redis配置、封装帮助类RedisHelper及使用实例
本文目录 1. 摘要 2. Redis配置 3. RedisHelper 4.使用实例 5. 总结 1. 摘要 由于內存存取速度远高于磁盘读取的特性,为了程序效率提高性能,通常会把常用的不常变动的数 ...
- [C#] 使用 StackExchange.Redis 封装属于自己的 RedisHelper
使用 StackExchange.Redis 封装属于自己的 RedisHelper 目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List ...
- RedisHelper帮助类
using Newtonsoft.Json; using RedLockNet.SERedis; using RedLockNet.SERedis.Configuration; using Stack ...
- RedisHelper in C#
自己写了一个RedisHelper,现贴出来,希望各位大神能够指正和优化. using System; using StackExchange.Redis; using System.Configur ...
- 使用 StackExchange.Redis 封装属于自己的 RedisHelper
目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List) 有序集合(sorted set) Key 操作 发布订阅 其他 简介 目前 .NE ...
- RedisHelper Redis帮助类
using StackExchange.Redis; using System; using System.Collections.Generic; using System.IO; using Sy ...
- Redis:RedisHelper(5)
/// <summary> /// Redis 助手 /// </summary> public class RedisHelper { /// <summary> ...
随机推荐
- something just like this---About Me
endl:JX弱校oier,04年生,妹子,2019级高一新生,然后居然不知道该说什么了,尴尬 2019年3月开始接触oi,学的很慢(看起来脑子不太好用) 2019年7月创建了这个博客,在收到“恭喜! ...
- PHP实现Redis分布式锁
锁在我们的日常开发可谓用得比较多.通常用来解决资源并发的问题.特别是多机集群情况下,资源争抢的问题.但是,很多新手在锁的处理上常常会犯一些问题.今天我们来深入理解锁. 一.Redis 锁错误使用之一 ...
- Linux系统管理图文详解超详细精心整理
前言:带你遨游于linux系统管理知识的海洋,沐浴春日里的阳光,循序渐进,看完之后收获满满. 本次讲解基于linux(centos6.5)虚拟机做的测试,centos7估计以后有时间再更新啊. lin ...
- FCN用卷积层代替FC层原因(转)
原博客连接 : https://www.cnblogs.com/byteHuang/p/6959714.html CNN对于常见的分类任务,基本是一个鲁棒且有效的方法.例如,做物体分类的话,入门级别的 ...
- SSM定时任务(spring3.0)
SSM定时任务主要分为两部分 1.applicationContext.xml配置文件设置 设置如下: 在xmlns中添加:xmlns:task="http://www.springfram ...
- 易优CMS:arcview的基础用法
[基础用法] 名称:arcview 功能:获取单条文档数据 语法: {eyou:arcview aid='文档ID'} <a href="{$field.arcurl}"&g ...
- vue浏览器全屏实现
1.项目中使用的是sreenfull插件,执行命令安装 npm install --save screenfull 2.安装好后,引入项目,用一个按钮进行控制即可,按钮方法如下: toggleFull ...
- momentjs在vue中的用法
js代码 import moment from 'moment'; const jsCountDown = document.getElementById('js-countdown'); const ...
- Zeppelie连接jdbc的使用
1. 下载 wget http://apache.mirror.cdnetworks.com/zeppelin/zeppelin-0.8.1/zeppelin-0.8.1-bin-all.tgz 2. ...
- 文:你可以杀我,但你不能评价(judge)我
原创 豆瓣影评:“现代战争启示录”豆友影评 2006-12-18 20:24:20 本文刊载于<豆瓣影评>豆友“芹泽虾饺菌”的影评 原文标题<剃刀边缘的疯狂> 文/芹泽虾饺菌 ...