From 30be8816c0fe88625e1775c0518188aa8207e720 Mon Sep 17 00:00:00 2001 From: zhangbin <460190368@qq.com> Date: Thu, 26 Jun 2025 11:28:43 +0800 Subject: [PATCH] =?UTF-8?q?redis=20=E5=A4=9A=E7=94=A8=E6=88=B7=E6=8E=A7?= =?UTF-8?q?=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Infrastructure/Cache/RedisCacheContext.cs | 40 +++++- .../ServiceApp/Response/MqttClientResp.cs | 33 +++++ .../AirportMaintenanceController.cs | 126 +++++++++++++++++- OpenAuth.WebApi/Startup.cs | 10 +- 4 files changed, 202 insertions(+), 7 deletions(-) create mode 100644 OpenAuth.App/ServiceApp/Response/MqttClientResp.cs diff --git a/Infrastructure/Cache/RedisCacheContext.cs b/Infrastructure/Cache/RedisCacheContext.cs index b37a42c..1374eec 100644 --- a/Infrastructure/Cache/RedisCacheContext.cs +++ b/Infrastructure/Cache/RedisCacheContext.cs @@ -170,9 +170,47 @@ namespace Infrastructure.Cache return iDatabase.ListLength(key); } - public IEnumerable GetAllKeys(string pattern) + public IEnumerable GetAllKeys(string pattern) { return server.Keys(pattern: new RedisValue(pattern)); } + /// + /// HSET - 异步设置哈希表中的多个字段。 + /// + /// + /// + /// + public void HashSetAsync(RedisKey key, HashEntry[] hashFields, CommandFlags flags = CommandFlags.None) + { + iDatabase.HashSetAsync(key, hashFields, CommandFlags.None); + } + /// + /// HGETALL - 异步获取哈希表中的所有字段和值。 + /// + /// + /// + /// + public Task HashGetAllAsync(RedisKey key, CommandFlags flags = CommandFlags.None) + { + return iDatabase.HashGetAllAsync(key, CommandFlags.None); + } + /// + /// Returns all the members of the set value stored at key + /// + /// + /// + /// + public Task SetMembersAsync(RedisKey key, CommandFlags flags = CommandFlags.None) + { + return iDatabase.SetMembersAsync(key, CommandFlags.None); + } + public Task SetAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) + { + return iDatabase.SetAddAsync(key, value, CommandFlags.None); + } + public Task SetRemoveAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) + { + return iDatabase.SetRemoveAsync(key, value, CommandFlags.None); + } } } \ No newline at end of file diff --git a/OpenAuth.App/ServiceApp/Response/MqttClientResp.cs b/OpenAuth.App/ServiceApp/Response/MqttClientResp.cs new file mode 100644 index 0000000..22603af --- /dev/null +++ b/OpenAuth.App/ServiceApp/Response/MqttClientResp.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAuth.App.ServiceApp.Response +{ + public class MqttClientResp + { + /// + /// 客户端ID + /// + public string ClientId { get; set; } + /// + /// 用户id + /// + public string UserId { get; set; } + /// + /// 用户名 + /// + public string UserName { get; set; } + /// + /// 连接时间 + /// + public DateTime ConnectTime { get; set; } + /// + /// 是否控制 + /// + public bool IsLock { get; set; } + + } +} diff --git a/OpenAuth.WebApi/Controllers/ServiceControllers/AirportMaintenanceController.cs b/OpenAuth.WebApi/Controllers/ServiceControllers/AirportMaintenanceController.cs index a692a8b..28e4df9 100644 --- a/OpenAuth.WebApi/Controllers/ServiceControllers/AirportMaintenanceController.cs +++ b/OpenAuth.WebApi/Controllers/ServiceControllers/AirportMaintenanceController.cs @@ -1,13 +1,18 @@ -using DocumentFormat.OpenXml.Math; +using DocumentFormat.OpenXml.EMMA; +using DocumentFormat.OpenXml.Math; using DocumentFormat.OpenXml.Spreadsheet; using Infrastructure; +using Infrastructure.Cache; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MQTTnet; using OpenAuth.App.ServiceApp; +using OpenAuth.App.ServiceApp.Response; using OpenAuth.Repository.Domain; +using StackExchange.Redis; using System.Text; using System.Text.Json; +using System.Threading.Tasks; namespace OpenAuth.WebApi.Controllers.ServiceControllers { @@ -21,12 +26,14 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers private readonly AirportMaintenanceApp _app; private readonly MqttClientManager _mqttClientManager; private readonly MqttMessageCenter _mqttCenter; + private readonly RedisCacheContext _cache; - public AirportMaintenanceController(AirportMaintenanceApp app, MqttClientManager mqttClientManager, MqttMessageCenter mqttCenter) + public AirportMaintenanceController(AirportMaintenanceApp app, MqttClientManager mqttClientManager, MqttMessageCenter mqttCenter, RedisCacheContext cache) { _app = app; _mqttClientManager = mqttClientManager; _mqttCenter = mqttCenter; + _cache = cache; } /// /// 机场注册 注册码生成 @@ -389,5 +396,120 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers return response; } + + + #region redis 多用户控制 + /// + /// 添加修改mqtt客户端信息 + /// + /// + /// + [HttpPost] + [AllowAnonymous] + public async Task> AddOrUpdateRedisUser(MqttClientResp info) + { + var result = new Response(); + try + { + var clientKey = $"client:{info.UserId}"; + string lockSetKey = "locked_users"; + + // 查询所有锁定用户 + var existingLocked = await _cache.SetMembersAsync(lockSetKey); + + // 如果有锁定用户,并且锁定的用户不是当前用户,则拒绝 + if (existingLocked.Length > 0 && info.IsLock == true) + { + bool isCurrentUserLocked = existingLocked.Any(u => u == info.UserId); + if (!isCurrentUserLocked) + { + result.Code = 400; + result.Message = "已有其他用户处于锁定状态,不能添加新的锁定用户。"; + result.Result = false; + return result; + } + } + + // 存客户端信息 + _cache.HashSetAsync(clientKey, new HashEntry[] + { + new("ClientId", info.ClientId), + new("UserId", info.UserId), + new("UserName", info.UserName), + new("ConnectTime", info.ConnectTime.ToString("O")), + new("IsLock", info.IsLock ? "true" : "false") + }); + + if (info.IsLock) + { + await _cache.SetAddAsync(lockSetKey, info.UserId); + } + else + { + await _cache.SetRemoveAsync(lockSetKey, info.UserId); + } + result.Result = true; + } + catch (Exception ex) + { + result.Code = 500; + result.Message = ex.Message; + } + return result; + } + /// + /// 获取当前用户mqtt客户端信息 + /// + /// + /// + [HttpGet] + [AllowAnonymous] + public async Task> GetRedisUser(string id) + { + var result = new Response(); + try + { + result.Result = ParseClient(await _cache.HashGetAllAsync($"client:{id}")); + } + catch (Exception ex) + { + result.Code = 500; + result.Message = ex.Message; + } + return result; + } + private MqttClientResp ParseClient(HashEntry[] entries) + { + var dict = entries.ToDictionary(e => e.Name.ToString(), e => e.Value.ToString()); + return new MqttClientResp + { + ClientId = dict["ClientId"], + UserId = dict["UserId"], + UserName = dict["UserName"], + ConnectTime = DateTime.Parse(dict["ConnectTime"]), + IsLock = bool.Parse(dict["IsLock"]) + }; + } + /// + /// 获取所有锁定的用户客户端信息 + /// + /// + [HttpGet] + [AllowAnonymous] + public async Task> GetLockedClients() + { + var userIds = await _cache.SetMembersAsync("locked_users"); + + var result = new List(); + + foreach (var userId in userIds) + { + var entries = await _cache.HashGetAllAsync($"client:{userId}"); + if (entries.Length > 0) + result.Add(ParseClient(entries)); + } + return result; + } + #endregion } } diff --git a/OpenAuth.WebApi/Startup.cs b/OpenAuth.WebApi/Startup.cs index 12cb679..4680c69 100644 --- a/OpenAuth.WebApi/Startup.cs +++ b/OpenAuth.WebApi/Startup.cs @@ -4,6 +4,7 @@ using Autofac.Extensions.DependencyInjection; using ce.autofac.extension; using IdentityServer4.AccessTokenValidation; using Infrastructure; +using Infrastructure.Cache; using Infrastructure.CloudSdk.minio; using Infrastructure.CloudSdk.mqttmessagecenter; using Infrastructure.Extensions.AutofacManager; @@ -217,6 +218,7 @@ namespace OpenAuth.WebApi #region MemoryCache services.AddMemoryCache(); + services.AddSingleton(); #endregion @@ -327,10 +329,10 @@ namespace OpenAuth.WebApi #region mqtt services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); + //services.AddSingleton(); + //services.AddSingleton(); + //services.AddSingleton(); + //services.AddSingleton(); services.AddSingleton(); services.AddHostedService();