• .net core下Redis帮助类


        0.引入.net core环境下Redis的NuGet包,StackExchange.Redis,现目前最新的2.0.519。
           

    1. 帮助类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 出错
      ", 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? expiry = default(TimeSpan?))
      100         {
      101             return CacheRedis.StringSet(key, value, expiry);
      102         }
      103 
      104         /// <summary>
      105         /// 保存多个key value
      106         /// </summary>
      107         /// <param name="arr">key</param>
      108         /// <returns></returns>
      109         public bool StringSet(KeyValuePair<RedisKey, RedisValue>[] arr)
      110         {
      111             return CacheRedis.StringSet(arr);
      112         }
      113 
      114         /// <summary>
      115         /// 批量存值
      116         /// </summary>
      117         /// <param name="keysStr">key</param>
      118         /// <param name="valuesStr">The value.</param>
      119         /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
      120         public bool StringSetMany(string[] keysStr, string[] valuesStr)
      121         {
      122             var count = keysStr.Length;
      123             var keyValuePair = new KeyValuePair<RedisKey, RedisValue>[count];
      124             for (int i = 0; i < count; i++)
      125             {
      126                 keyValuePair[i] = new KeyValuePair<RedisKey, RedisValue>(keysStr[i], valuesStr[i]);
      127             }
      128 
      129             return CacheRedis.StringSet(keyValuePair);
      130         }
      131 
      132         /// <summary>
      133         /// 保存一个对象
      134         /// </summary>
      135         /// <typeparam name="T"></typeparam>
      136         /// <param name="key"></param>
      137         /// <param name="obj"></param>
      138         /// <returns></returns>
      139         public bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
      140         {
      141             string json = JsonConvert.SerializeObject(obj);
      142             return CacheRedis.StringSet(key, json, expiry);
      143         }
      144 
      145         /// <summary>
      146         /// 追加值
      147         /// </summary>
      148         /// <param name="key"></param>
      149         /// <param name="value"></param>
      150         public void StringAppend(string key, string value)
      151         {
      152             ////追加值,返回追加后长度
      153             long appendlong = CacheRedis.StringAppend(key, value);
      154         }
      155 
      156         /// <summary>
      157         /// 获取单个key的值
      158         /// </summary>
      159         /// <param name="key">Redis Key</param>
      160         /// <returns></returns>
      161         public RedisValue GetStringKey(string key)
      162         {
      163             return CacheRedis.StringGet(key);
      164         }
      165 
      166         /// <summary>
      167         /// 根据Key获取值
      168         /// </summary>
      169         /// <param name="key">键值</param>
      170         /// <returns>System.String.</returns>
      171         public string StringGet(string key)
      172         {
      173             try
      174             {
      175                 return CacheRedis.StringGet(key);
      176             }
      177             catch (Exception ex)
      178             {
      179                 Log.Debug("RedisHelper->StringGet 出错
      ", ex.Message.ToString());
      180                 return null;
      181             }
      182         }
      183 
      184         /// <summary>
      185         /// 获取多个Key
      186         /// </summary>
      187         /// <param name="listKey">Redis Key集合</param>
      188         /// <returns></returns>
      189         public RedisValue[] GetStringKey(List<RedisKey> listKey)
      190         {
      191             return CacheRedis.StringGet(listKey.ToArray());
      192         }
      193 
      194         /// <summary>
      195         /// 批量获取值
      196         /// </summary>
      197         public string[] StringGetMany(string[] keyStrs)
      198         {
      199             var count = keyStrs.Length;
      200             var keys = new RedisKey[count];
      201             var addrs = new string[count];
      202 
      203             for (var i = 0; i < count; i++)
      204             {
      205                 keys[i] = keyStrs[i];
      206             }
      207             try
      208             {
      209 
      210                 var values = CacheRedis.StringGet(keys);
      211                 for (var i = 0; i < values.Length; i++)
      212                 {
      213                     addrs[i] = values[i];
      214                 }
      215                 return addrs;
      216             }
      217             catch (Exception ex)
      218             {
      219                 Log.Debug("RedisHelper->StringGetMany 出错
      ", ex.Message.ToString());
      220                 return null;
      221             }
      222         }
      223 
      224         /// <summary>
      225         /// 获取一个key的对象
      226         /// </summary>
      227         /// <typeparam name="T"></typeparam>
      228         /// <param name="key"></param>
      229         /// <returns></returns>
      230         public T GetStringKey<T>(string key)
      231         {
      232             return JsonConvert.DeserializeObject<T>(CacheRedis.StringGet(key));
      233         }
      234         #endregion
      235 
      236 
      237         #region --删除设置过期--
      238         /// <summary>
      239         /// 删除单个key
      240         /// </summary>
      241         /// <param name="key">redis key</param>
      242         /// <returns>是否删除成功</returns>
      243         public bool KeyDelete(string key)
      244         {
      245             return CacheRedis.KeyDelete(key);
      246         }
      247 
      248         /// <summary>
      249         /// 删除多个key
      250         /// </summary>
      251         /// <param name="keys">rediskey</param>
      252         /// <returns>成功删除的个数</returns>
      253         public long KeyDelete(RedisKey[] keys)
      254         {
      255             return CacheRedis.KeyDelete(keys);
      256         }
      257 
      258         /// <summary>
      259         /// 判断key是否存储
      260         /// </summary>
      261         /// <param name="key">redis key</param>
      262         /// <returns></returns>
      263         public bool KeyExists(string key)
      264         {
      265             return CacheRedis.KeyExists(key);
      266         }
      267 
      268         /// <summary>
      269         /// 重新命名key
      270         /// </summary>
      271         /// <param name="key">就的redis key</param>
      272         /// <param name="newKey">新的redis key</param>
      273         /// <returns></returns>
      274         public bool KeyRename(string key, string newKey)
      275         {
      276             return CacheRedis.KeyRename(key, newKey);
      277         }
      278 
      279         /// <summary>
      280         /// 删除hasekey
      281         /// </summary>
      282         /// <param name="key"></param>
      283         /// <param name="hashField"></param>
      284         /// <returns></returns>
      285         public bool HaseDelete(RedisKey key, RedisValue hashField)
      286         {
      287             return CacheRedis.HashDelete(key, hashField);
      288         }
      289 
      290         /// <summary>
      291         /// 移除hash中的某值
      292         /// </summary>
      293         /// <typeparam name="T"></typeparam>
      294         /// <param name="key"></param>
      295         /// <param name="dataKey"></param>
      296         /// <returns></returns>
      297         public bool HashRemove(string key, string dataKey)
      298         {
      299             return CacheRedis.HashDelete(key, dataKey);
      300         }
      301 
      302         /// <summary>
      303         /// 设置缓存过期
      304         /// </summary>
      305         /// <param name="key"></param>
      306         /// <param name="datetime"></param>
      307         public void SetExpire(string key, DateTime datetime)
      308         {
      309             CacheRedis.KeyExpire(key, datetime);
      310         }
      311         #endregion
      312     }
      313 }
      View Code
    2. using引用备注:
      using Newtonsoft.Json;//为第三方转json 对象使用的,再熟悉不过了吧
      using YJT.Common.Log;//是一个记录日志的帮助的类,你可以用你自己的来记录日志。
      using YJT.Web.lib;//此引用是获取.net core中的appsettings.json中配置的信息。 UtilConf.Configuration["RedisConfig:ReadWriteHosts"]获取
    3. 获取appsettings.json的UtilConf.cs帮助类:
       1 using Microsoft.Extensions.Configuration;
       2 using System;
       3 using System.Collections.Generic;
       4 using System.IO;
       5 using System.Text;
       6 
       7 namespace YJT.Web.lib
       8 {
       9     /// <summary>
      10     /// 读配置文件
      11     /// </summary>
      12     public class UtilConf
      13     {
      14         private static IConfiguration config;
      15 
      16         /// <summary>
      17         /// 加载配置文件
      18         /// </summary>
      19         public static IConfiguration Configuration
      20         {
      21             get
      22             {
      23                 if (config != null) return config;
      24                 config = new ConfigurationBuilder()
      25                     .SetBasePath(Directory.GetCurrentDirectory())
      26                     .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      27                     .Build();
      28                 return config;
      29             }
      30             set => config = value;
      31         }
      32     }
      33 }
      View Code

      此类主要是获取.net core 中的json配置信息。如:UtilConf.Configuration["RedisConfig:ReadWriteHosts"]

    4. StackExchange.Redis下的IDatabase接口还有丰富的操作方法,可自行研究补充帮助类

      分享至此,欢迎留言评论~~~

  • 相关阅读:
    Python脚本模拟登陆DVWA
    PHP单元测试使用
    PHPUnit实践一(初识)
    composer引用本地git做为源库
    编写自己的composer项目
    Laravel 核心--Facades 门面
    Laravel5 创建自定义门面(Facade)
    简单理解laravel框架中的服务容器,服务提供者以及怎样调用服务
    Laravel自带SMTP邮件组件实现发送邮件(QQ、163、企业邮箱都可)
    cocos2d-x游戏开发系列教程-坦克大战游戏之坦克和地图碰撞的检测下
  • 原文地址:https://www.cnblogs.com/CDLinXi/p/10472025.html
Copyright © 2020-2023  润新知