using IM_API.Interface.Services; using IM_API.Models; using IM_API.Tools; using Microsoft.Extensions.Caching.Distributed; using System.Text.Json; namespace IM_API.Services { public class RedisCacheService:ICacheService { private readonly IDistributedCache _cache; public RedisCacheService(IDistributedCache cache) { _cache = cache; } public async Task GetAsync(string key) { var valueBytes= await _cache.GetAsync(key); if (valueBytes is null || valueBytes.Length == 0) return default; return JsonSerializer.Deserialize(valueBytes); } public async Task GetUserCacheAsync(string username) { var usernameKey = RedisKeys.GetUserinfoKeyByUsername(username); var userid = await GetAsync(usernameKey); if (userid is null) return default; var key = RedisKeys.GetUserinfoKey(userid); return await GetAsync(key); } public async Task RemoveAsync(string key) => await _cache.RemoveAsync(key); public async Task RemoveUserCacheAsync(string username) { var usernameKey = RedisKeys.GetUserinfoKeyByUsername(username); var userid = await GetAsync(usernameKey); if (userid is null) return; var key = RedisKeys.GetUserinfoKey(userid); await RemoveAsync(key); } public async Task SetAsync(string key, T value, TimeSpan? expiration = null) { var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = expiration ?? TimeSpan.FromHours(1) }; var valueBytes = JsonSerializer.SerializeToUtf8Bytes(value); await _cache.SetAsync(key, valueBytes, options); } public async Task SetUserCacheAsync(User user) { var idKey = RedisKeys.GetUserinfoKey(user.Id.ToString()); await SetAsync(idKey, user); var usernameKey = RedisKeys.GetUserinfoKeyByUsername(user.Username); await SetAsync(usernameKey, user.Id.ToString()); } } }