.NetCore 使用StackExchange.Redis 连接Redis

StackExchange.Redis是一个.Net平台上使用较为广泛的一个Redis封装

 

1.安装Redis

前提是得先在本机上安装Redis,由于我是在window上,访问以下链接下载windows安装包

https://github.com/microsoftarchive/redis/releases 

若是安装在linux中,则直接访问redis.io ,redis官网上有linux安装包

打开链接后,找到最新的release稳定版,选择msi后缀的安装包,下载,如图:

.NetCore 使用StackExchange.Redis 连接Redis_第1张图片

下载完毕后,安装即可

具体步骤可参考:https://www.cnblogs.com/jaign/articles/7920588.html

 

2.打开VS2019,新建一个.NetCore项目,选择API,如图:

.NetCore 使用StackExchange.Redis 连接Redis_第2张图片

 

3.创建后,先引入StackExchange.Redis的Nuget包,如下图:

.NetCore 使用StackExchange.Redis 连接Redis_第3张图片

 

 

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

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RedisConnectionString": "127.0.0.1,password=123456,DefaultDatabase=0"
  }
}

 

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

RedisClient.cs 帮助类,如下:

using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace redisTest
{
    public class RedisClient
    {
        private static readonly object Locker = new object();

        private ConnectionMultiplexer redisMultiplexer;

        IDatabase db = null;

        private static RedisClient _redisClient = null;
        public static RedisClient redisClient
        {
            get
            {
                if (_redisClient == null)
                {
                    lock (Locker)
                    {
                        if (_redisClient == null)
                        {
                            _redisClient = new RedisClient();

                        }
                    }
                }
                return _redisClient;
            }
        }

        public void InitConnect(IConfiguration Configuration)
        {
            try
            {
                var RedisConnection = Configuration.GetConnectionString("RedisConnectionString");
                redisMultiplexer = ConnectionMultiplexer.Connect(RedisConnection);
                db = redisMultiplexer.GetDatabase();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                redisMultiplexer = null;
                db = null;
            }
        }

        public RedisClient()
        {

        }


        #region String 
        /// 
        /// 保存单个key value
        /// 
        /// 保存的值
        /// 过期时间
        public bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?))
        {
            return db.StringSet(key, value, expiry);
        }

        /// 
        /// 获取单个key的值
        /// 
        public RedisValue GetStringKey(string key)
        {
            return db.StringGet(key);
        }


        /// 
        /// 获取一个key的对象
        /// 
        public T GetStringKey(string key)
        {
            if (db == null)
            {
                return default;
            }
            var value = db.StringGet(key);
            if (value.IsNullOrEmpty)
            {
                return default;
            }
            return JsonConvert.DeserializeObject(value);
        }

        /// 
        /// 保存一个对象
        /// 
        /// 
        public bool SetStringKey(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
    }
}

 

 

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

Startup.cs文件如下:

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 redisTest
{
    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.最后,修改下默认的ValueController.cs

ValueController.cs如下:

using System;using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace redisTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult Get(int id)
        {
            var redisResult = RedisClient.redisClient.GetStringKey("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();//有则直接返回
        }
    }
}

 

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

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

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

 

附上项目截图:

.NetCore 使用StackExchange.Redis 连接Redis_第4张图片

 

本文简单介绍了下.NetCore Web项目中使用StackExchange.Redis的方法

你可能感兴趣的:(Asp,.Net,Core,Redis)