欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net core下Redis帮助类

程序员文章站 2022-04-28 11:40:24
0.引入.net core环境下Redis的NuGet包,StackExchange.Redis,现目前最新的2.0.519。 1 using System; 2 using System.Collections.Generic; 3 using StackExchange.Redis; 4 usi ......

    0.引入.net core环境下redis的nuget包,stackexchange.redis,现目前最新的2.0.519。
      .net core下Redis帮助类 

  1. 帮助类code:
    .net core下Redis帮助类
      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? 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 出错\r\n", 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 出错\r\n", 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帮助类:
    .net core下Redis帮助类
     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"]

    .net core下Redis帮助类

     

  4. stackexchange.redis下的idatabase接口还有丰富的操作方法,可自行研究补充帮助类
    .net core下Redis帮助类

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