This commit is contained in:
2026-02-08 15:13:55 +08:00
parent ed95bdddac
commit 46472f03e6
10 changed files with 124 additions and 39 deletions
+39 -1
View File
@@ -6,6 +6,7 @@ using IM_API.Models;
using IM_API.Tools;
using Microsoft.EntityFrameworkCore;
using StackExchange.Redis;
using System.Text.Json;
namespace IM_API.Services
{
@@ -15,12 +16,16 @@ namespace IM_API.Services
private readonly ILogger<UserService> _logger;
private readonly IMapper _mapper;
private readonly ICacheService _cacheService;
public UserService(ImContext imContext,ILogger<UserService> logger,IMapper mapper, ICacheService cacheService)
private readonly IDatabase _redis;
public UserService(
ImContext imContext,ILogger<UserService> logger,
IMapper mapper, ICacheService cacheService, IConnectionMultiplexer connectionMultiplexer)
{
this._context = imContext;
this._logger = logger;
this._mapper = mapper;
_cacheService = cacheService;
_redis = connectionMultiplexer.GetDatabase();
}
#region
public async Task<UserInfoDto> GetUserInfoAsync(int userId)
@@ -87,5 +92,38 @@ namespace IM_API.Services
return _mapper.Map<UserInfoDto>(user);
}
#endregion
#region
public async Task<List<UserInfoDto>> GetUserInfoListAsync(List<int> ids)
{
//读取缓存中存在的用户,存在直接添加到结果列表
var idKeyArr = ids.Select(s => (RedisKey)RedisKeys.GetUserinfoKey(s.ToString())).ToArray();
var values = await _redis.StringGetAsync(idKeyArr);
List<User> results = [];
List<int> missingIds = [];
for(int i = 0; i < ids.Count; i++)
{
if (values[i].HasValue)
{
results.Add(JsonSerializer.Deserialize<User>(values[i]));
}
else
{
missingIds.Add(ids[i]);
}
}
//如果存在没有缓存的用户则进行查库
if (missingIds.Any())
{
var dbUsers = await _context.Users
.Where(x => ids.Contains(x.Id)).ToListAsync();
results.AddRange(dbUsers);
var setTasks = dbUsers.Select(s => _cacheService.SetUserCacheAsync(s)).ToList();
await Task.WhenAll(setTasks);
}
return _mapper.Map<List<UserInfoDto>>(results);
}
#endregion
}
}