0
0
mirror of https://github.com/alex289/CleanArchitecture.git synced 2025-06-30 02:31:08 +00:00

feat: Add redis cache

This commit is contained in:
alex289 2023-08-31 21:08:46 +02:00
parent f46994c60a
commit a742ae6dc0
No known key found for this signature in database
GPG Key ID: 573F77CD2D87F863
18 changed files with 204 additions and 21 deletions

View File

@ -17,6 +17,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="7.0.10"/>
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="7.0.10" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="7.0.10"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0"/>
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0"/>

View File

@ -56,6 +56,19 @@ builder.Services.AddLogging(x => x.AddSimpleConsole(console =>
console.IncludeScopes = true;
}));
if (builder.Environment.IsProduction())
{
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration["RedisHostName"];
options.InstanceName = "clean-architecture";
});
}
else
{
builder.Services.AddDistributedMemoryCache();
}
var app = builder.Build();
using (var scope = app.Services.CreateScope())

View File

@ -13,5 +13,6 @@
"Issuer": "CleanArchitectureServer",
"Audience": "CleanArchitectureClient",
"Secret": "sD3v061gf8BxXgmxcHssasjdlkasjd87439284)@#(*"
}
},
"RedisHostName": "redis"
}

View File

@ -6,20 +6,26 @@ using CleanArchitecture.Application.Queries.Tenants.GetAll;
using CleanArchitecture.Application.Queries.Tenants.GetTenantById;
using CleanArchitecture.Application.ViewModels;
using CleanArchitecture.Application.ViewModels.Tenants;
using CleanArchitecture.Domain;
using CleanArchitecture.Domain.Commands.Tenants.CreateTenant;
using CleanArchitecture.Domain.Commands.Tenants.DeleteTenant;
using CleanArchitecture.Domain.Commands.Tenants.UpdateTenant;
using CleanArchitecture.Domain.Entities;
using CleanArchitecture.Domain.Extensions;
using CleanArchitecture.Domain.Interfaces;
using Microsoft.Extensions.Caching.Distributed;
namespace CleanArchitecture.Application.Services;
public sealed class TenantService : ITenantService
{
private readonly IMediatorHandler _bus;
private readonly IDistributedCache _distributedCache;
public TenantService(IMediatorHandler bus)
public TenantService(IMediatorHandler bus, IDistributedCache distributedCache)
{
_bus = bus;
_distributedCache = distributedCache;
}
public async Task<Guid> CreateTenantAsync(CreateTenantViewModel tenant)
@ -47,7 +53,16 @@ public sealed class TenantService : ITenantService
public async Task<TenantViewModel?> GetTenantByIdAsync(Guid tenantId, bool deleted)
{
return await _bus.QueryAsync(new GetTenantByIdQuery(tenantId, deleted));
var cachedTenant = await _distributedCache.GetOrCreateJsonAsync(
CacheKeyGenerator.GetEntityCacheKey<Tenant>(tenantId),
async () => await _bus.QueryAsync(new GetTenantByIdQuery(tenantId, deleted)),
new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromDays(3),
AbsoluteExpiration = DateTimeOffset.Now.AddDays(30)
});
return cachedTenant;
}
public async Task<PagedResult<TenantViewModel>> GetAllTenantsAsync(PageQuery query, string searchTerm = "")

View File

@ -0,0 +1,13 @@
using System;
using CleanArchitecture.Domain.Entities;
namespace CleanArchitecture.Domain;
public static class CacheKeyGenerator
{
public static string GetEntityCacheKey<TEntity>(TEntity entity) where TEntity : Entity =>
$"{typeof(TEntity)}-{entity.Id}";
public static string GetEntityCacheKey<TEntity>(Guid id) where TEntity : Entity =>
$"{typeof(TEntity)}-{id}";
}

View File

@ -10,6 +10,7 @@
<PackageReference Include="FluentValidation" Version="11.7.1"/>
<PackageReference Include="MediatR" Version="12.1.1"/>
<PackageReference Include="Microsoft.Extensions.Options" Version="7.0.1"/>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.32.1"/>
</ItemGroup>

View File

@ -100,7 +100,7 @@ public sealed class CreateUserCommandHandler : CommandHandlerBase,
if (await CommitAsync())
{
await Bus.RaiseEventAsync(new UserCreatedEvent(user.Id));
await Bus.RaiseEventAsync(new UserCreatedEvent(user.Id, user.TenantId));
}
}
}

View File

@ -62,7 +62,7 @@ public sealed class DeleteUserCommandHandler : CommandHandlerBase,
if (await CommitAsync())
{
await Bus.RaiseEventAsync(new UserDeletedEvent(request.UserId));
await Bus.RaiseEventAsync(new UserDeletedEvent(request.UserId, user.TenantId));
}
}
}

View File

@ -100,7 +100,7 @@ public sealed class UpdateUserCommandHandler : CommandHandlerBase,
if (await CommitAsync())
{
await Bus.RaiseEventAsync(new UserUpdatedEvent(user.Id));
await Bus.RaiseEventAsync(new UserUpdatedEvent(user.Id, user.TenantId));
}
}
}

View File

@ -1,7 +1,9 @@
using System.Threading;
using System.Threading.Tasks;
using CleanArchitecture.Domain.Entities;
using CleanArchitecture.Domain.Events.Tenant;
using MediatR;
using Microsoft.Extensions.Caching.Distributed;
namespace CleanArchitecture.Domain.EventHandler;
@ -10,18 +12,29 @@ public sealed class TenantEventHandler :
INotificationHandler<TenantDeletedEvent>,
INotificationHandler<TenantUpdatedEvent>
{
private readonly IDistributedCache _distributedCache;
public TenantEventHandler(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
public Task Handle(TenantCreatedEvent notification, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task Handle(TenantDeletedEvent notification, CancellationToken cancellationToken)
public async Task Handle(TenantDeletedEvent notification, CancellationToken cancellationToken)
{
return Task.CompletedTask;
await _distributedCache.RemoveAsync(
CacheKeyGenerator.GetEntityCacheKey<Tenant>(notification.AggregateId),
cancellationToken);
}
public Task Handle(TenantUpdatedEvent notification, CancellationToken cancellationToken)
public async Task Handle(TenantUpdatedEvent notification, CancellationToken cancellationToken)
{
return Task.CompletedTask;
await _distributedCache.RemoveAsync(
CacheKeyGenerator.GetEntityCacheKey<Tenant>(notification.AggregateId),
cancellationToken);
}
}

View File

@ -1,7 +1,9 @@
using System.Threading;
using System.Threading.Tasks;
using CleanArchitecture.Domain.Entities;
using CleanArchitecture.Domain.Events.User;
using MediatR;
using Microsoft.Extensions.Caching.Distributed;
namespace CleanArchitecture.Domain.EventHandler;
@ -11,23 +13,36 @@ public sealed class UserEventHandler :
INotificationHandler<UserUpdatedEvent>,
INotificationHandler<PasswordChangedEvent>
{
private readonly IDistributedCache _distributedCache;
public UserEventHandler(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
public Task Handle(PasswordChangedEvent notification, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task Handle(UserCreatedEvent notification, CancellationToken cancellationToken)
public async Task Handle(UserCreatedEvent notification, CancellationToken cancellationToken)
{
return Task.CompletedTask;
await _distributedCache.RemoveAsync(
CacheKeyGenerator.GetEntityCacheKey<Tenant>(notification.TenantId),
cancellationToken);
}
public Task Handle(UserDeletedEvent notification, CancellationToken cancellationToken)
public async Task Handle(UserDeletedEvent notification, CancellationToken cancellationToken)
{
return Task.CompletedTask;
await _distributedCache.RemoveAsync(
CacheKeyGenerator.GetEntityCacheKey<Tenant>(notification.TenantId),
cancellationToken);
}
public Task Handle(UserUpdatedEvent notification, CancellationToken cancellationToken)
public async Task Handle(UserUpdatedEvent notification, CancellationToken cancellationToken)
{
return Task.CompletedTask;
await _distributedCache.RemoveAsync(
CacheKeyGenerator.GetEntityCacheKey<Tenant>(notification.TenantId),
cancellationToken);
}
}

View File

@ -5,7 +5,10 @@ namespace CleanArchitecture.Domain.Events.User;
public sealed class UserCreatedEvent : DomainEvent
{
public UserCreatedEvent(Guid userId) : base(userId)
public Guid TenantId { get; }
public UserCreatedEvent(Guid userId, Guid tenantId) : base(userId)
{
TenantId = tenantId;
}
}

View File

@ -5,7 +5,10 @@ namespace CleanArchitecture.Domain.Events.User;
public sealed class UserDeletedEvent : DomainEvent
{
public UserDeletedEvent(Guid userId) : base(userId)
public Guid TenantId { get; }
public UserDeletedEvent(Guid userId, Guid tenantId) : base(userId)
{
TenantId = tenantId;
}
}

View File

@ -5,7 +5,10 @@ namespace CleanArchitecture.Domain.Events.User;
public sealed class UserUpdatedEvent : DomainEvent
{
public UserUpdatedEvent(Guid userId) : base(userId)
public Guid TenantId { get; }
public UserUpdatedEvent(Guid userId, Guid tenantId) : base(userId)
{
TenantId = tenantId;
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
namespace CleanArchitecture.Domain.Extensions;
public static class DistributedCacheExtensions
{
private static readonly JsonSerializerSettings s_jsonSerializerSettings = new()
{
TypeNameHandling = TypeNameHandling.All
};
public static async Task<T?> GetOrCreateJsonAsync<T>(
this IDistributedCache cache,
string key,
Func<Task<T?>> factory,
DistributedCacheEntryOptions options,
CancellationToken cancellationToken = default) where T : class
{
var json = await cache.GetStringAsync(key, cancellationToken);
if (!string.IsNullOrWhiteSpace(json))
{
return JsonConvert.DeserializeObject<T>(json, s_jsonSerializerSettings)!;
}
var value = await factory();
if (value == default)
{
return value;
}
json = JsonConvert.SerializeObject(value, s_jsonSerializerSettings);
await cache.SetStringAsync(key, json, options, cancellationToken);
return value;
}
}

View File

@ -39,7 +39,7 @@ public sealed class InMemoryBusTests
var inMemoryBus = new InMemoryBus(mediator, domainEventStore);
var userDeletedEvent = new UserDeletedEvent(Guid.NewGuid());
var userDeletedEvent = new UserDeletedEvent(Guid.NewGuid(), Guid.NewGuid());
await inMemoryBus.RaiseEventAsync(userDeletedEvent);

View File

@ -22,3 +22,16 @@ services:
- SA_PASSWORD=Password123!#
ports:
- 1433:1433
redis:
image: docker.io/bitnami/redis:7.2
environment:
# ALLOW_EMPTY_PASSWORD is recommended only for development.
- ALLOW_EMPTY_PASSWORD=yes
- REDIS_DISABLE_COMMANDS=FLUSHDB,FLUSHALL
ports:
- '6379:6379'
volumes:
- 'redis_data:/bitnami/redis/data'
volumes:
redis_data:
driver: local

View File

@ -70,4 +70,50 @@ spec:
- protocol: TCP
port: 1433
targetPort: 1433
type: ClusterIP
type: ClusterIP
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis-deployment
spec:
replicas: 1
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
containers:
- name: redis
image: docker.io/bitnami/redis:7.2
env:
# ALLOW_EMPTY_PASSWORD is recommended only for development.
- name: ALLOW_EMPTY_PASSWORD
value: "yes"
- name: REDIS_DISABLE_COMMANDS
value: "FLUSHDB,FLUSHALL"
ports:
- containerPort: 6379
volumeMounts:
- name: redis-data
mountPath: /bitnami/redis/data
volumes:
- name: redis-data
emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
name: redis-service
spec:
selector:
app: redis
ports:
- protocol: TCP
port: 6379
targetPort: 6379