Add caches
This commit is contained in:
@@ -118,16 +118,38 @@ public class PostgreSqlUserRepository : BaseRepositoryWithLogging, IUserReposito
|
||||
{
|
||||
return await ExecuteWithLoggingAsync(async () =>
|
||||
{
|
||||
// Check cache first for all users
|
||||
var cacheKey = "all_users";
|
||||
var cachedUsers = _cacheService.GetValue<List<User>>(cacheKey);
|
||||
if (cachedUsers != null)
|
||||
{
|
||||
return cachedUsers;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await PostgreSqlConnectionHelper.EnsureConnectionOpenAsync(_context);
|
||||
|
||||
// Optimized query with explicit SELECT to avoid loading unnecessary data
|
||||
var userEntities = await _context.Users
|
||||
.AsNoTracking()
|
||||
.Select(u => new UserEntity
|
||||
{
|
||||
Id = u.Id,
|
||||
Name = u.Name,
|
||||
AgentName = u.AgentName,
|
||||
AvatarUrl = u.AvatarUrl,
|
||||
TelegramChannel = u.TelegramChannel
|
||||
})
|
||||
.ToListAsync()
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return userEntities.Select(PostgreSqlMappers.Map);
|
||||
var users = userEntities.Select(PostgreSqlMappers.Map).ToList();
|
||||
|
||||
// Cache all users for 10 minutes since this data changes infrequently
|
||||
_cacheService.SaveValue(cacheKey, users, TimeSpan.FromMinutes(10));
|
||||
|
||||
return users;
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -182,6 +204,9 @@ public class PostgreSqlUserRepository : BaseRepositoryWithLogging, IUserReposito
|
||||
{
|
||||
_cacheService.SaveValue(newUserAgentCacheKey, user, TimeSpan.FromMinutes(5));
|
||||
}
|
||||
|
||||
// Invalidate all users cache since we added a new user
|
||||
_cacheService.RemoveValue("all_users");
|
||||
return; // Exit early since we already saved
|
||||
}
|
||||
|
||||
@@ -204,6 +229,9 @@ public class PostgreSqlUserRepository : BaseRepositoryWithLogging, IUserReposito
|
||||
var newAgentCacheKey = $"user_agent_{user.AgentName}";
|
||||
_cacheService.RemoveValue(newAgentCacheKey);
|
||||
}
|
||||
|
||||
// Invalidate all users cache since we updated a user
|
||||
_cacheService.RemoveValue("all_users");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user