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> ...
随机推荐
- PHPStorm使用PHP7新特性出现红色波浪错误
今天在项目中使用PHP7新特性时PHPStorm出现了如下红色错误,看着让人很不舒服,明明没有错 本地配置LNMP的PHP版本是7.2所以不是安装的PHP版本过低的问题,而是PHPStorm默认支持的 ...
- IDA+Windbg IDA+OD 连动调试插件
https://github.com/bootleg/ret-sync 使用注意事项:多次测试,最好现在IDA中启动,然后再在OD或WINDBG(.load sync)中启动. 这个工具还是相当给力的 ...
- Maven的assembly插件在linux启动卡住Starting the localhost.localdomain
1.今天在测试assembly的时候,在Linux虚拟机,内存配置为512mb,然后开始在Linux上运行assembly的时候就会一直卡住 2.停止运行后,查看了下日志 [root@localho ...
- 死磕 java同步系列之Semaphore源码解析
问题 (1)Semaphore是什么? (2)Semaphore具有哪些特性? (3)Semaphore通常使用在什么场景中? (4)Semaphore的许可次数是否可以动态增减? (5)Semaph ...
- .net core入门-项目启动时报错:HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure
在打开Core的项目首页时,页面有时候会出现:HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure的错误,但是这里面看不出任何错误详情,这个时候 ...
- 用PHP写出计算器
<body> <?php if (!empty($_POST)) { $op=$_POST['point']; $sum1 = $_POST['sum1']; $sum2 = $_P ...
- DevExpress的下拉框控件ComboxBoxEdit怎样绑定键值对选项
场景 DevExpress的下拉框控件ComboBoxEdit控件的使用: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/1028 ...
- media适配css
/*引入适配的less*/ html { font-size: 16px; } @media only screen and (min-width: 320px) { html { font-size ...
- 用canvas画一个时钟
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- xml解析-jaxp添加结点
jaxp添加结点 eg: //在第一个下面添加nv / 1.创建解析器工厂 * 2.根据解析器工厂创建解析器 * 3.解析xml返回document * * 4.得到第一个p1 * -得到所有p1使用 ...