<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#)的更多相关文章

  1. 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 ...

  2. C# Azure 存储-分布式缓存Redis工具类 RedisHelper

    using System; using System.Collections.Generic; using Newtonsoft.Json; using StackExchange.Redis; na ...

  3. Asp.Net Core 2.0 项目实战(6)Redis配置、封装帮助类RedisHelper及使用实例

    本文目录 1. 摘要 2. Redis配置 3. RedisHelper 4.使用实例 5. 总结 1.  摘要 由于內存存取速度远高于磁盘读取的特性,为了程序效率提高性能,通常会把常用的不常变动的数 ...

  4. [C#] 使用 StackExchange.Redis 封装属于自己的 RedisHelper

    使用 StackExchange.Redis 封装属于自己的 RedisHelper 目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List ...

  5. RedisHelper帮助类

    using Newtonsoft.Json; using RedLockNet.SERedis; using RedLockNet.SERedis.Configuration; using Stack ...

  6. RedisHelper in C#

    自己写了一个RedisHelper,现贴出来,希望各位大神能够指正和优化. using System; using StackExchange.Redis; using System.Configur ...

  7. 使用 StackExchange.Redis 封装属于自己的 RedisHelper

    目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List) 有序集合(sorted set) Key 操作 发布订阅 其他 简介 目前 .NE ...

  8. RedisHelper Redis帮助类

    using StackExchange.Redis; using System; using System.Collections.Generic; using System.IO; using Sy ...

  9. Redis:RedisHelper(5)

    /// <summary> /// Redis 助手 /// </summary> public class RedisHelper { /// <summary> ...

随机推荐

  1. dva+umi+antd项目从搭建到使用(没有剖验证,不知道在说i什么)

    先创建一个新项目,具体步骤请参考https://www.cnblogs.com/darkbluelove/p/11338309.html 一.添加document.ejs文件(参考文档:https:/ ...

  2. 《细说PHP》第四版 样章 第18章 数据库抽象层PDO 12

    18.9  管理表books实例 在Web项目中,几乎所有模块都要和数据表打交道,而对表的管理无非就是增.删.改.查等操作,所以熟练掌握对表进行管理的这些常见操作是十分有必的.本例为了能更好地展示PD ...

  3. 【VM配置】配置主机名称、网卡和yum源配置

    一,.配置主机名 为了对主机能进行分区,除了要有ip地址外还需要主机名,主机之间可以通过这个类似域名的名称来相互访问.linux系统中主机名配置文件一般在/etc/hostname文件中.另外我们也可 ...

  4. laravel中select2多选,初始化默认选中项

    项目中有发送消息功能,需要能通过搜索,多选用户,来指定发送人.使用 select2 插件来完成. select2 的 html 代码如下: <div class="form-group ...

  5. java war包 路径--解决war包中文件路径问题

    https://blog.csdn.net/u013409283/article/details/51480948 转自:http://free-chenwei.iteye.com/blog/1507 ...

  6. 在.net core程序中使用EntityFrameok(非EF Core)

    最近用NoSQL较多写,用传统的EF到不多,但在一些.net core小程序中也小试牛刀过,不过当时用的是微软为.net core量身定制的Entity Framework Core,只是一些比较常规 ...

  7. 2018-2-13-win10-uwp-切换主题

    原文:2018-2-13-win10-uwp-切换主题 title author date CreateTime categories win10 uwp 切换主题 lindexi 2018-2-13 ...

  8. NET EF 连接Oracle 的配置方法记录

    主要记录下如何在EF 中连接Oracle s数据库,很傻瓜式,非常简单,但是不知道的童鞋,也会搞得很难受,我自己就是 1.创一个控制台程序,并且添加  Oracle.ManagedDataAccess ...

  9. go-面向对象编程(上)

    一个程序就是一个世界,有很多对象(变量) Golang 语言面向对象编程说明 1) Golang 也支持面向对象编程(OOP),但是和传统的面向对象编程有区别,并不是纯粹的面向对 象语言.所以我们说 ...

  10. 深入理解JVM,7种垃圾收集器

    本人免费整理了Java高级资料,一共30G,需要自己领取.传送门:https://mp.weixin.qq.com/s/JzddfH-7yNudmkjT0IRL8Q 如果说收集算法是内存回收的方法论, ...