<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. 拎壶学python3-----(1)输出与字符转换

    一.输入自己的名字打印 二.数字和字符串是不能相加的如下 怎么解决上边的问题呢? 如果是相加我们要把字符串转成数字类型如下 如果不想让他相加可以写成这样如下: ok,关于转换就先讲到这里

  2. elasticsearch 索引的使用(配合haystack)

    1,# 从仓库拉取镜像$ sudo docker image pull delron/elasticsearch-ik:2.4.6-1.02,下载elasticsearc-2.4.6目录拷贝到home ...

  3. iota: Golang 中优雅的常量

    阅读约 11 分钟 注:该文作者是 Katrina Owen,原文地址是 iota: Elegant Constants in Golang 有些概念有名字,并且有时候我们关注这些名字,甚至(特别)是 ...

  4. SpringBoot(六) SpringBoot整合Swagger2(自动化生成接口文档)

    一:在上篇文章pom增加依赖: <dependency> <groupId>io.springfox</groupId> <artifactId>spr ...

  5. SpringCloud之API网关与服务发现——Cloud核心组件实战入门及原理

    微服务发展历史 单体模式——>服务治理(服务拆分)——>微服务(细分服务)——>Segments(服务网格) 微服务 VS SOA 微服务:模块化.独立部署.异构化 SOA:共同的治 ...

  6. Taro多端自定义导航栏Navbar+Tabbar实例

    运用Taro实现多端导航栏/tabbar实例 (H5 + 小程序 + React Native) 最近一直在捣鼓taro开发,虽说官网介绍支持编译到多端,但是网上大多数实例都是H5.小程序,很少有支持 ...

  7. HTTP协议解析之Cookie

    " Cookie与身份认证." 提到HTTP协议,不可避免地都会牵涉到Cookie,可以说,Cookie作为HTTP的重要组成部分,促进了HTTP协议的发展壮大. HTTP协议如果 ...

  8. C# 第三方库

    基本上选用的都是 https://www.nuget.org 分类中最流行的那个库 1. 日志工具库 NLOG Stackify.com 简单入门文章  https://stackify.com/nl ...

  9. SpringBoot+Thyemelaf开发环境正常,打包jar发到服务器就报错Template might not exist or might not be accessible

    这里说一下Thyemelaf的巨坑 写了一个SpringBoot+Thyemelaf的项目,并不是前后端分离.今天想放到linux服务器上玩玩,打成jar包,然后一运行他妈居然报错了,报了一个Temp ...

  10. SRDC - ORA-1628: Checklist of Evidence to Supply (Doc ID 1682729.1)

    SRDC - ORA-1628: Checklist of Evidence to Supply (Doc ID 1682729.1) Action Plan 1. Execute srdc_db_u ...