NetCore 使用 redis
Redis是什么?
Redis是一个开源的、使用C语言编写的、支持网络交互的、可基于内存也可持久化的Key-Value数据库。
第一步:下载Redis,并安装
下载连接:https://github.com/microsoftarchive/redis/releases
安装之后,出现Redis服务
第二步:配置环境变量
在path中新建
%REDIS_HOME%
第三步:测试环境变量是否配置成功
redis-cli -h 127.0.0.1
第四步:使用C#连接redis
添加nuget包:StackExchange.Redis
1、创建Redis公共类(RedisCacheManager.cs、 IRedisCacheManager.cs)
接口:
public interface IRedisService { /// <summary> /// 清除Redis /// </summary> public void Clear(); /// <summary> /// 是否存在Key /// </summary> public bool Exists(string key); /// <summary> /// 获取Redis /// </summary> public string Get(string key); /// <summary> /// 获取Redis /// </summary> public TEntity Get<TEntity>(string key); /// <summary> /// 移除Redis /// </summary> public void Remove(string key); /// <summary> /// 设置Redis /// </summary> public void Set(string key, object value, TimeSpan cacheTime); /// <summary> /// 设置Redis /// </summary> public bool Set(string key, byte[] value); }
实现:
public class RedisService : IRedisService { private readonly string redisConnenctionString; public volatile ConnectionMultiplexer redisConnection; private readonly object redisConnectionLock = new object(); public RedisService(int point = 6379) { this.redisConnenctionString = $"127.0.0.1:{point}"; this.redisConnection = GetRedisConnection(); } /// <summary> /// 核心代码,获取连接实例 /// 通过双if 夹lock的方式,实现单例模式 /// </summary> /// <returns></returns> private ConnectionMultiplexer GetRedisConnection() { //如果已经连接实例,直接返回 if (this.redisConnection != null && this.redisConnection.IsConnected) { return this.redisConnection; } //加锁,防止异步编程中,出现单例无效的问题 lock (redisConnectionLock) { if (this.redisConnection != null) { //释放redis连接 this.redisConnection.Dispose(); } try { this.redisConnection = ConnectionMultiplexer.Connect(redisConnenctionString); } catch (Exception) { throw new Exception("Redis服务未启用,请开启该服务"); } } return this.redisConnection; } /// <summary> /// 清除Redis /// </summary> public void Clear() { foreach (var endPoint in this.GetRedisConnection().GetEndPoints()) { var server = this.GetRedisConnection().GetServer(endPoint); foreach (var key in server.Keys()) { redisConnection.GetDatabase().KeyDelete(key); } } } /// <summary> /// 是否存在Key /// </summary> public bool Exists(string key) { return redisConnection.GetDatabase().KeyExists(key); } /// <summary> /// 获取Redis /// </summary> public string Get(string key) { return redisConnection.GetDatabase().StringGet(key); } /// <summary> /// 获取Redis /// </summary> public TEntity Get<TEntity>(string key) { if (!Exists(key)) return default(TEntity); var value = redisConnection.GetDatabase().StringGet(key); if (value.HasValue) { //需要用的反序列化,将Redis存储的Byte[],进行反序列化 var jsonString = Encoding.UTF8.GetString(value); return JsonSerializer.Deserialize<TEntity>(Encoding.UTF8.GetString(value)); } return default(TEntity); } /// <summary> /// 移除Redis /// </summary> public void Remove(string key) { if (Exists(key)) { redisConnection.GetDatabase().KeyDelete(key); } } /// <summary> /// 设置Redis /// </summary> public void Set(string key, object value, TimeSpan cacheTime) { if (value != null) { //序列化,将object值生成RedisValue var jsonString = JsonSerializer.Serialize(value); redisConnection.GetDatabase().StringSet(key, Encoding.UTF8.GetBytes(jsonString), cacheTime); } } /// <summary> /// 设置Redis /// </summary> public bool Set(string key, byte[] value) { return redisConnection.GetDatabase().StringSet(key, value, TimeSpan.FromSeconds(120)); } }
2、 注入
builder.Services.AddSingleton<IRedisService, RedisService>();
3、控制器使用
private readonlyIRedisService
_redisService; public WeatherForecastController(IRedisService
redisService) { _redisService = redisService; } [HttpGet("Redis")] public async Task<IActionResult> Redis(int id) { string key = "RedisKey1"; var user = new UserModel(); if (_redisCacheManager.Get<object>(key) != null) { user = _redisCacheManager.Get<UserModel>(key); } else { user = new UserModel { UserId = DateTime.Now.Ticks.ToString(), UserName = "micro" }; _redisCacheManager.Set(key, user, TimeSpan.FromHours(2));//缓存2小时 } return Ok(user); }
实体类(UserModel.cs)
public class UserModel { public string? UserId { set; get; } public string? UserName { set; get; } }
运行结果:
示例源码下载
方案二:
static ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect("localhost"); static void Main(string[] args) { IDatabase db = redisClient.GetDatabase(); // Set db.StringSet("city", "城市"); // Get db.StringGet("city"); int age = (int)db.StringGet("age"); // 删除 db.KeyDelete("city"); // 监听消息队列messages ISubscriber sub = redisClient.GetSubscriber(); sub.Subscribe("messages", (channel, message) => { Console.WriteLine((string)message); }); // 进队 for (int i = 1; i < 10; i++) { Thread.Sleep(1000); sub.Publish("messages", "hello" + i); } Console.ReadLine(); }