ASP.NET Core 消息队列----Redis

-

一、安装Redis,如图下载以下2个安装文件,一个redis服务,一个redis桌面管理工具

1.png

二、安装完,通过任务管理器找到redis 右键启动


三、配置Redis缓存方式

Redis的数据都存放在内存中,如果没有配置持久化,redis重启后数据就全丢失了,于是需要开启redis的持久化功能,将数据保存到磁 盘上,当redis重启后,可以从磁盘中恢复数据。redis提供两种方式进行持久化,一种是RDB持久化(原理是将Reids在内存中的数据库记录定时 dump到磁盘上的RDB持久化),另外一种是AOF(append only file)持久化(原理是将Reids的操作日志以追加的方式写入文件)。那么这两种持久化方式有什么区别呢,改如何选择呢?网上看了大多数都是介绍这两 种方式怎么配置,怎么使用,就是没有介绍二者的区别,在什么应用场景下使用。

4.png


3.png

RDB持久化配置

Redis会将数据集的快照dump到dump.rdb文件中。此外,我们也可以通过配置文件来修改Redis服务器dump快照的频率,在打开6379.conf文件之后,我们搜索save,可以看到下面的配置信息:

save 900 1              #在900秒(15分钟)之后,如果至少有1个key发生变化,则dump内存快照。

save 300 10            #在300秒(5分钟)之后,如果至少有10个key发生变化,则dump内存快照。

save 60 10000        #在60秒(1分钟)之后,如果至少有10000个key发生变化,则dump内存快照。

AOF持久化配置

在Redis的配置文件中存在三种同步方式,它们分别是:

appendfsync always     #每次有数据修改发生时都会写入AOF文件。

appendfsync everysec  #每秒钟同步一次,该策略为AOF的缺省策略。

appendfsync no          #从不同步。高效但是数据不会被持久化。


我一般采用AOF,去配置一下,找到redis安装目录 C:\Program Files (x86)\Redis\conf  找到  redis.conf

①、appendonly属性 默认是RDB存储,把no改为yes

②、appendfilename :aof文件名,默认是"appendonly.aof"

③、appendfsync:aof持久化策略的配置;no表示不执行fsync,由操作系统保证数据同步到磁盘,速度最快;always表示每次写入都执行fsync,以保证数据同步到磁盘;everysec表示每秒执行一次fsync,可能会导致丢失这1s数据

保存,重启服务,去安装目录查看文件data里面的文件 存在即表示成功

5.png

四、NET6实战Redis

1. NuGet安装 ServiceStack.Redis,安装版本跟框架版本保持一致

2. 创建缓存接口

/// <summary>
/// 缓存接口
/// </summary>
public interface ICache
{
    #region Key-Value
    /// <summary>
    /// 读取缓存
    /// </summary>
    /// <param name="cacheKey">键</param>
    /// <returns></returns>
    T GetCache<T>(string cacheKey, long dbId = 0) where T : class;
    /// <summary>
    /// 写入缓存
    /// </summary>
    /// <param name="value">对象数据</param>
    /// <param name="cacheKey">键</param>
    void WriteCache<T>(T value, string cacheKey, long dbId = 0) where T : class;
    /// <summary>
    /// 写入缓存
    /// </summary>
    /// <param name="value">对象数据</param>
    /// <param name="cacheKey">键</param>
    /// <param name="expireTime">到期时间</param>
    void WriteCache<T>(T value, string cacheKey, DateTime expireTime, long dbId = 0) where T : class;

    /// <summary>
    /// 移除指定数据缓存
    /// </summary>
    /// <param name="cacheKey">键</param>
    void RemoveCache(string cacheKey, long dbId = 0);
    /// <summary>
    /// 移除全部缓存
    /// </summary>
    void RemoveCache(long dbId = 0);
    #endregion
}

3. 创建缓存类

 public class Cache : ICache
 {
     #region Key-Value
     public T GetCache(string cacheKey, long dbId = 0) where T : class
     {
         return RedisCache.Get(cacheKey, dbId);
     }
      public void WriteCache(T value, string cacheKey, long dbId = 0) where T : class
     {
         RedisCache.Set(cacheKey, value, dbId);
     }
     public void WriteCache(T value, string cacheKey,  DateTime expireTime, long dbId = 0) where T : class
     {
         RedisCache.Set(cacheKey, value, expireTime, dbId);
     }
    
     public void RemoveCache(string cacheKey, long dbId = 0)
     {
         RedisCache.Remove(cacheKey, dbId);
     }
     public void RemoveCache(long dbId = 0)
     {
         RedisCache.RemoveAll(dbId);
     }
 
     #endregion
 }

3.创建缓存公用类

 public class RedisCache
 {
     #region -- 连接信息 --
     // redis配置文件信息 
     private static PooledRedisClientManager prcm;
 
     // 创建链接池管理对象
        private static PooledRedisClientManager CreateManager(long dbId=0)
     {
         string[] writeServerList = SplitString(AppSettings.app(new string[] { "Redis", "WriteServerList" }), ",");
         string[] readServerList = SplitString(AppSettings.app(new string[] { "Redis", "ReadServerList" }), ",");

         return new PooledRedisClientManager(readServerList, writeServerList,
                          new RedisClientManagerConfig
                          {
                              MaxWritePoolSize = int.Parse(AppSettings.app(new string[] { "Redis", "MaxWritePoolSize" })),
                              MaxReadPoolSize = int.Parse(AppSettings.app(new string[] { "Redis", "MaxReadPoolSize" })),
                              AutoStart = (AppSettings.app(new string[] { "Redis", "AutoStart" })=="true"),
                              DefaultDb =(int)dbId
                          });

     }
     private static string[] SplitString(string strSource, string split)
     {
         return strSource.Split(split.ToArray());
     }
     private static PooledRedisClientManager GetClientManager(long dbId)
     {
         return CreateManager(dbId);
     }
     #endregion

     #region -- Item --
      public static bool Set(string key, T t, long dbId = 0)
     {
         var clientManager = GetClientManager(dbId);
         IRedisClient redis = clientManager.GetClient();
         var res = redis.Set(key, t);
         clientManager.DisposeClient((RedisNativeClient)redis);
         redis.Dispose();
         clientManager.Dispose();
         return res;
     }
     public static bool Set(string key, T t, TimeSpan timeSpan, long dbId = 0)
     {
         var clientManager = GetClientManager(dbId);
         IRedisClient redis = clientManager.GetClient();
         var res = redis.Set(key, t, timeSpan);
         clientManager.DisposeClient((RedisNativeClient)redis);
         redis.Dispose();
         clientManager.Dispose();
         return res;
     }
     public static bool Set(string key, T t, DateTime dateTime, long dbId = 0)
     {
         var clientManager = GetClientManager(dbId);
         IRedisClient redis = clientManager.GetClient();
         var res = redis.Set(key, t, dateTime);
         clientManager.DisposeClient((RedisNativeClient)redis);
         redis.Dispose();
         clientManager.Dispose();
         return res;
     }

      public static T Get(string key, long dbId = 0) where T : class
     {
         var clientManager = GetClientManager(dbId);
         IRedisClient redis = clientManager.GetClient();
         var res = redis.Get(key);
         clientManager.DisposeClient((RedisNativeClient)redis);
         redis.Dispose();
         clientManager.Dispose();
         return res;
     }
     public static bool Remove(string key, long dbId = 0)
     {
         var clientManager = GetClientManager(dbId);
         IRedisClient redis = clientManager.GetClient();
         var res = redis.Remove(key);
         clientManager.DisposeClient((RedisNativeClient)redis);
         redis.Dispose();
         clientManager.Dispose();
         return res;
     }
      public static void RemoveAll(long dbId = 0)
     {
         var clientManager = GetClientManager(dbId);
         IRedisClient redis = clientManager.GetClient();
         redis.FlushDb();
         clientManager.DisposeClient((RedisNativeClient)redis);
         redis.Dispose();
         clientManager.Dispose();
     }
     #endregion

     #region -- List --
    public static void List_Add(string key, T t, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var redisTypedClient = redis.As();
             redisTypedClient.AddItemToList(redisTypedClient.Lists[key], t);
         }
     }
    public static bool List_Remove(string key, T t, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var redisTypedClient = redis.As();
             return redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], t) > 0;
         }
     }
      public static void List_RemoveAll(string key, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var redisTypedClient = redis.As();
             redisTypedClient.Lists[key].RemoveAll();
         }
     }
     public static long List_Count(string key, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             return redis.GetListCount(key);
         }
     }
      public static List List_GetRange(string key, int start, int count, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var c = redis.As();
             return c.Lists[key].GetRange(start, start + count - 1);
         }
     }
      public static List List_GetList(string key, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var c = redis.As();
             return c.Lists[key].GetRange(0, c.Lists[key].Count);
         }
     }
  public static List List_GetList(string key, int pageIndex, int pageSize, long dbId = 0)
     {
         int start = pageSize * (pageIndex - 1);
         return List_GetRange(key, start, pageSize, dbId);
     }
     #endregion

     #region -- Set --
      public static void Set_Add(string key, T t, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
           
             var redisTypedClient = redis.As();
             
             redisTypedClient.Sets[key].Add(t);
         }
     }
        public static bool Set_Contains(string key, T t, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var redisTypedClient = redis.As();
             return redisTypedClient.Sets[key].Contains(t);
         }
     }
       public static bool Set_Remove(string key, T t, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var redisTypedClient = redis.As();
             return redisTypedClient.Sets[key].Remove(t);
         }
     }
     #endregion

     #region -- Hash --
      public static bool Hash_Exist(string key, string dataKey, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             return redis.HashContainsEntry(key, dataKey);
         }
     }

     public static bool Hash_Set(string key, string dataKey, T t, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             string value = ServiceStack.Text.JsonSerializer.SerializeToString(t);
             return redis.SetEntryInHash(key, dataKey, value);
         }
     }
     public static bool Hash_Remove(string key, string dataKey, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             return redis.RemoveEntryFromHash(key, dataKey);
         }
     }
     public static bool Hash_Remove(string key, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             return redis.Remove(key);
         }
     }
     public static T Hash_Get(string key, string dataKey, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             string value = redis.GetValueFromHash(key, dataKey);
             return ServiceStack.Text.JsonSerializer.DeserializeFromString(value);
         }
     }
     public static List Hash_GetAll(string key, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var list = redis.GetHashValues(key);
             if (list != null && list.Count > 0)
             {
                 List result = new List();
                 foreach (var item in list)
                 {
                     var value = ServiceStack.Text.JsonSerializer.DeserializeFromString(item);
                     result.Add(value);
                 }
                 return result;
             }
             return null;
         }
     }
     #endregion

     #region -- SortedSet --
    public static bool SortedSet_Add(string key, T t, double score, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             string value = ServiceStack.Text.JsonSerializer.SerializeToString(t);
             return redis.AddItemToSortedSet(key, value, score);
         }
     }
    public static bool SortedSet_Remove(string key, T t, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             string value = ServiceStack.Text.JsonSerializer.SerializeToString(t);
             return redis.RemoveItemFromSortedSet(key, value);
         }
     }
    public static long SortedSet_Trim(string key, int size, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             return redis.RemoveRangeFromSortedSet(key, size, 9999999);
         }
     }
     public static long SortedSet_Count(string key, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             return redis.GetSortedSetCount(key);
         }
     }
      public static List SortedSet_GetList(string key, int pageIndex, int pageSize, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var list = redis.GetRangeFromSortedSet(key, (pageIndex - 1) * pageSize, pageIndex * pageSize - 1);
             if (list != null && list.Count > 0)
             {
                 List result = new List();
                 foreach (var item in list)
                 {
                     var data = ServiceStack.Text.JsonSerializer.DeserializeFromString(item);
                     result.Add(data);
                 }
                 return result;
             }
         }
         return null;
     }

      public static List SortedSet_GetListALL(string key, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             var list = redis.GetRangeFromSortedSet(key, 0, 9999999);
             if (list != null && list.Count > 0)
             {
                 List result = new List();
                 foreach (var item in list)
                 {
                     var data = ServiceStack.Text.JsonSerializer.DeserializeFromString(item);
                     result.Add(data);
                 }
                 return result;
             }
         }
         return null;
     }
     #endregion

     #region 公用方法
      public static void SetExpire(string key, DateTime datetime, long dbId = 0)
     {
         using (IRedisClient redis = CreateManager(dbId).GetClient())
         {
             redis.ExpireEntryAt(key, datetime);
         }
     }
     #endregion
 }

4. 注册缓存服务

builder.Services.AddScoped(typeof(ICache), typeof(Cache));

5. appsettings.json 配置redis属性

  "Redis": {
    "ConnectionString": "127.0.0.1:6379",
    "WriteServerList": "127.0.0.1:6379",
    "ReadServerList": "127.0.0.1:6379",
    "MaxWritePoolSize": 60,
    "MaxReadPoolSize": 60,
    "AutoStart": "true",
    "LocalCacheTime": "180",
    "RecordeLog": "false"

  }

6.创建测试程序

    public class DemoTestController : ControllerBase
    {
        private ICache cache;
        public DemoTestController(ICache caches)
        {
            cache = caches;
        }
    [HttpGet]
    public ContentResult InRedisData() {
       // 参数: value,key,expireTime,dbid
        cache.WriteCache("存入Db2", "InRedisData",DateTime.Today.AddDays(3),2);
        return Content("执行完成");
    }
    [HttpGet]
    public ContentResult UPRedisData()
    {
        //新数据写入会直接覆盖
        cache.WriteCache("这是修改的Db2", "InRedisData", DateTime.Today.AddDays(3), 2);
        return Content("执行完成");
    }
    [HttpGet]
    public ContentResult DelRedisData()
    {
        cache.RemoveCache("InRedisData", 2);
        return Content("执行完成");
    }


其他配置可参考:https://zhuanlan.zhihu.com/p/144917964?utm_id=0

docker 安装redis:https://blog.csdn.net/weixin_46906696/article/details/126560996

相关文章!
  • ASP.NET Core 消息队列---

    Dapr (Distributed Application Runtime)是一个可移植的、事件驱动的运行时,它使任何开发人员都可以轻松地构建运行在云和边缘上的弹性

  • ASP.NET Core 消息队列---

  • ASP.NET Core 消息队列---

    RabbitMQ从信息接收者角度可以看做三种模式,一对一,一对多(此一对多并不是发布订阅,而是每条信息只有一个接收者)和发布订阅。其中一对