asp.net core使用redis实现分布式缓存
首先Windows安装redis并将redis设置成服务
参考网址:https://blog.csdn.net/Mrqiang9001/article/details/79428976
注意:修改redis.windows.conf文件 设置密码requirepass和注释掉bind ip使得外网可以访问 另外服务器端口6379记得打开
引用包StackExchange.Redis
<PackageReference Include="StackExchange.Redis" Version="2.1.30" />
一、添加配置(appsettings.json)
"ConnectionStrings": { "Redis": "XXX.XX.XX.XXX,password=******,DefaultDatabase=0" },
二、添加服务依赖(Startup.cs)
RedisClient.redisClient.InitConnect(Configuration);
三、redis帮助类(RedisClient)
using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Text; namespace Dw.Util.Helper { 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 = ConfigHelper.GetValue("ConnectionStrings:Redis"); redisMultiplexer = ConnectionMultiplexer.Connect(RedisConnection); db = redisMultiplexer.GetDatabase(); } catch (Exception ex) { Console.WriteLine(ex.Message); redisMultiplexer = null; db = null; } } public RedisClient() { } /// <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); } } }
四、在控制器中使用
#region Redis测试 /// <summary> /// Redis测试 /// </summary> /// <returns></returns> [Route("Redis")] [HttpGet] public ActionResult Redis() { var redisResult = RedisClient.redisClient.GetStringKey("myKey"); return Ok(new { code = "200", res = new { msg = redisResult.ToString() } }); } #endregion