隐藏

.NetCore Redis使用及帮助类

发布:2022/1/25 17:39:37作者:管理员 来源:本站 浏览次数:931

这篇文章遗我们来说下 StackExchange.Redis的使用及帮助类

首先在windows上安装redis  在上边连接中有教程
1.创建net core项目

2.在包管理器中安装StackExchange.Redis的Nuget包,如下图:

4.在appsettings.json中添加connection连接字符串:(redis连接字符串)

 5.然后新建一个RedisClient.cs 帮助类,简单封装了一下redis的读写操作

    using Microsoft.Extensions.Configuration;
    using Newtonsoft.Json;
    using ServiceStack.Redis;
    using StackExchange.Redis;
    using System;
    using System.Collections.Generic;
    using System.Linq;
     
     
    namespace qq.Web.Host.Helper
    {
        public class RedisClient
        {
            static ConnectionMultiplexer redis = null;
            IDatabase db = null;
     
            public void InitConnect(IConfiguration Configuration)
            {
                try
                {
                    var RedisConnection = Configuration.GetConnectionString("RedisConnectionString");
                    redis = ConnectionMultiplexer.Connect(RedisConnection);
                    db = redis.GetDatabase();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    redis = null;
                    db = null;
                }
            }
            public RedisClient( )
            {
            }
            #region String
            /// <summary>
            /// 保存单个key value
            /// </summary>
            /// <param name="value">保存的值</param>
            /// <param name="expiry">过期时间</param>
            public bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?))
            {
                return db.StringSet(key, value, expiry);
            }
     
            /// <summary>
            /// 获取单个key的值
            /// </summary>
            public RedisValue GetStringKey(string key)
            {
                return db.StringGet(key);
            }
     
     
            /// <summary>
            /// 获取一个key的对象
            /// </summary>
            public T GetStringKey<T>(string key)
            {
                if (db == null)
                {
                    return default;
                }
                var value = db.StringGet(key);
                if (value.IsNullOrEmpty)
                {
                    return default;
                }
                return JsonConvert.DeserializeObject<T>(value);
            }
     
            /// <summary>
            /// 保存一个对象
            /// </summary>
            /// <param name="obj"></param>
            public bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
            {
                if (db == null)
                {
                    return false;
                }
                string json = JsonConvert.SerializeObject(obj);
                return db.StringSet(key, json, expiry);
            }
     
            #endregion
            /// <summary>
            /// 将一个泛型List添加到缓存中
            /// </summary>
            /// <typeparam name="T">泛型T</typeparam>
            /// <param name="listkey">Key</param>
            /// <param name="list">list</param>
            /// <param name="db_index">数据库序号,不传默认为0</param>
            /// <returns></returns>
            public bool addList<T>(string listkey, List<T> list, int db_index = 0)
            {
                if (db == null)
                {
                    return false;
                }
                var value = JsonConvert.SerializeObject(list);
                return db.StringSet(listkey, value);
     
            }
             
            /// <summary>
            /// 通过指定Key值获取泛型List
            /// </summary>
            /// <typeparam name="T">泛型T</typeparam>
            /// <param name="listkey">Key</param>
            /// <param name="db_index">数据库序号,不传默认为0</param>
            /// <returns></returns>
            public List<T> getList<T>(string listkey, int db_index = 0)
            {
                //var db = redis.GetDatabase(db_index);
                if (db == null)
                {
                    return new List<T>();
                }
                if (db.KeyExists(listkey))
                {
                    var value = db.StringGet(listkey);
                    if (!string.IsNullOrEmpty(value))
                    {
                        var list = JsonConvert.DeserializeObject<List<T>>(value);
                        return list;
                    }
                    else
                    {
                        return new List<T>();
                    }
                }
                else
                {
                    return new List<T>();
                }
            }
            public bool getKeyExists(string listkey, int db_index = 0)
            {
                if (db == null)
                {
                    return false;
                }
                if (db.KeyExists(listkey))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            /// <summary>
            /// 删除指定List<T>中满足条件的元素
            /// </summary>
            /// <param name="listkey">Key</param>
            /// <param name="func">lamdba表达式</param>
            /// <param name="db_index">数据库序号,不传默认为0</param>
            /// <returns></returns>
            public bool delListByLambda<T>(string listkey, Func<T, bool> func, int db_index = 0)
            {
                if (db == null)
                {
                    return false;
                }
                if (db.KeyExists(listkey))
                {
                    var value = db.StringGet(listkey);
                    if (!string.IsNullOrEmpty(value))
                    {
                        var list = JsonConvert.DeserializeObject<List<T>>(value);
                        if (list.Count > 0)
                        {
                            list = list.SkipWhile<T>(func).ToList();
                            value = JsonConvert.SerializeObject(list);
                            return db.StringSet(listkey, value);
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            /// <summary>
            /// 获取指定List<T>中满足条件的元素
            /// </summary>
            /// <param name="listkey">Key</param>
            /// <param name="func">lamdba表达式</param>
            /// <param name="db_index">数据库序号,不传默认为0</param>
            /// <returns></returns>
            public List<T> getListByLambda<T>(string listkey, Func<T, bool> func, int db_index = 0)
            {
                if (db == null)
                {
                    return new List<T>();
                }
                if (db.KeyExists(listkey))
                {
                    var value = db.StringGet(listkey);
                    if (!string.IsNullOrEmpty(value))
                    {
                        var list = JsonConvert.DeserializeObject<List<T>>(value);
                        if (list.Count > 0)
                        {
                            list = list.Where(func).ToList();
                            return list;
                        }
                        else
                        {
                            return new List<T>();
                        }
                    }
                    else
                    {
                        return new List<T>();
                    }
                }
                else
                {
                    return new List<T>();
                }
            }
        }
     
    }

6.在Startup.cs入口中 初始化RedisClient 的连接:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.HttpsPolicy;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
     
    namespace qqq.Web.Host.Helper
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
     
            public IConfiguration Configuration { get; }
     
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                //初始化redis
                RedisClient.redisClient.InitConnect(Configuration);//*******
            }
     
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseHsts();
                }
     
                app.UseHttpsRedirection();
                app.UseMvc();
            }
        }
    }

7.最后,在Controller.cs中调用

    using System;using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
     
    namespace qqq.Web.Host.Helper
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            // GET api/values/5
            [HttpGet]
            public ActionResult<string> Get(int id)
            {
                var redisResult = RedisClient.redisClient.GetStringKey<int>("key1");
                //若redis没有数据,则取数据并设置redis
                if (redisResult == null || redisResult == default(int))
                {
                    Console.WriteLine("redisResult is empty");
                    RedisClient.redisClient.SetStringKey("key1", id.ToString());
                    return id.ToString();
                }
                return redisResult.ToString();//有则直接返回
            }
         [HttpGet]
            public ActionResult GetList(string 简称, int 开始索引, int 限定数量) {
                try
                {//缓存中如果存在这个key返回查出的数据  如果不存在则写入缓存    查出数据后进行条件筛选和分页
     
                    List<dynamic> 列表 = null;
                    if (RedisClient.redisClient.getKeyExists("123"))
                    {
                        列表 = RedisClient.redisClient.getList("123");
                    }
                    else
                    {
                        RedisClient.redisClient.addList("123", GetDrugList());//插入key   和集合
                        列表 = RedisClient.redisClient.getList("123");
                    }
                    if (!string.IsNullOrEmpty(简称))
                    {
                        列表 = 列表.Where(x => x.首字母缩写.Contains(简称)).ToList();
                    }
                    if (列表.Count < 限定数量)
                    {
                        return Json(new { ok = false, msg = "sucess", data = 列表.GetRange(开始索引, 列表.Count) });
                    }
                    return Json(new { ok = false, msg = "sucess", data = 列表.GetRange(开始索引, 限定数量) });
                }
                catch (Exception ex)
                {
                    return Json(new { ok = false, msg = ex.Message, data = "" });
                }
            }
        }
    }

F5运行,输入:https://localhost:5001/api/values/100

返回100,此时redis中的数据库已经存入了 key1,100.

再次访问https://localhost:5001/api/values/99,还是会返回100,因为已经从redis中取数据了