0.引入.net core环境下Redis的NuGet包,StackExchange.Redis,现目前最新的2.0.519。
- 帮助类Code:
1 using System; 2 using System.Collections.Generic; 3 using StackExchange.Redis; 4 using Newtonsoft.Json; 5 using YJT.Web.lib; 6 using YJT.Common.Log; 7 8 namespace YJT.Web.Redis 9 { 10 /// <summary> 11 /// Redis帮助类 12 /// </summary> 13 public class RedisHelper 14 { 15 //单例模式 16 public static RedisCommon Default { get { return new RedisCommon(); } } 17 public static RedisCommon One { get { return new RedisCommon(1, UtilConf.Configuration["RedisConfig:ReadWriteHosts"] ?? "127.0.0.1:6789"); } } 18 public static RedisCommon Two { get { return new RedisCommon(2, UtilConf.Configuration["RedisConfig:ReadWriteHosts"] ?? "127.0.0.1:6789"); } } 19 public static RedisCommon Three { get { return new RedisCommon(3, UtilConf.Configuration["RedisConfig:ReadWriteHosts"] ?? "127.0.0.1:6789"); } } 20 } 21 22 /// <summary> 23 /// Redis操作类 24 /// 老版用的是ServiceStack.Redis 25 /// .Net Core使用StackExchange.Redis的nuget包 26 /// </summary> 27 public class RedisCommon 28 { 29 //redis数据库连接字符串 30 private string _conn = UtilConf.Configuration["RedisConfig:ReadWriteHosts"] ?? "127.0.0.1:6789"; 31 private int _db = 0; 32 33 //静态变量 保证各模块使用的是不同实例的相同链接 34 private static ConnectionMultiplexer connection; 35 36 /// <summary> 37 /// 构造函数 38 /// </summary> 39 public RedisCommon() { } 40 /// <summary> 41 /// 构造函数 42 /// </summary> 43 /// <param name="db"></param> 44 /// <param name="connectStr"></param> 45 public RedisCommon(int db, string connectStr) 46 { 47 _db = db; 48 _conn = connectStr; 49 } 50 51 /// <summary> 52 /// 缓存数据库,数据库连接 53 /// </summary> 54 public ConnectionMultiplexer CacheConnection 55 { 56 get 57 { 58 try 59 { 60 if (connection == null || !connection.IsConnected) 61 { 62 connection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_conn)).Value; 63 } 64 } 65 catch (Exception ex) 66 { 67 Log.Debug("RedisHelper->CacheConnection 出错\r\n", ex.Message.ToString()); 68 return null; 69 } 70 return connection; 71 } 72 } 73 74 /// <summary> 75 /// 缓存数据库 76 /// </summary> 77 public IDatabase CacheRedis => CacheConnection.GetDatabase(_db); 78 79 80 #region --KEY/VALUE存取-- 81 /// <summary> 82 /// 单条存值 83 /// </summary> 84 /// <param name="key">key</param> 85 /// <param name="value">The value.</param> 86 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> 87 public bool StringSet(string key, string value) 88 { 89 return CacheRedis.StringSet(key, value); 90 } 91 92 /// <summary> 93 /// 保存单个key value 94 /// </summary> 95 /// <param name="key">Redis Key</param> 96 /// <param name="value">保存的值</param> 97 /// <param name="expiry">过期时间</param> 98 /// <returns></returns> 99 public bool StringSet(string key, string value, TimeSpan? expir