Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Api/Microservice.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@

<ItemGroup>

<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="9.0.5" />

<ProjectReference Include="../Domain/Domain.csproj" />

<ProjectReference Include="../Infra/Infra.csproj" />
Expand Down
10 changes: 10 additions & 0 deletions src/Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Asp.Versioning.Builder;
using Domain.Interfaces;
using Domain.Services;
using Infra.Cache;
using Infra.Data;
using Infra.Repositories;
using Microsoft.EntityFrameworkCore;
Expand Down Expand Up @@ -49,6 +50,15 @@

builder.Host.UseSerilog();

builder.Services.AddMemoryCache();
builder.Services.AddStackExchangeRedisCache(opts =>
{
opts.Configuration = builder.Configuration.GetConnectionString("Redis");
opts.InstanceName = "SolutionTemplate:";
});
builder.Services.Configure<CacheManagerOptions>(builder.Configuration.GetSection("CacheOptions"));
builder.Services.AddSingleton<ICacheManager, CacheManager>();

var app = builder.Build();

app.UseHttpMetrics();
Expand Down
8 changes: 7 additions & 1 deletion src/Api/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@
},
"UseJsonFormat": false,
"ConnectionStrings": {
"PgpoolDb": ""
"PgpoolDb": "",
"Redis": ""
},
"CacheOptions": {
"UseDistributedCache": false,
"MemoryCacheDuration": "00:02:00",
"DistributedCacheDuration": "00:10:00"
}
}
11 changes: 11 additions & 0 deletions src/Domain/Interfaces/ICacheManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;

namespace Domain.Interfaces
{
public interface ICacheManager
{
Task<T?> GetAsync<T>(string key);
Task SetAsync<T>(string key, T value);
Task RemoveAsync(string key);
}
}
29 changes: 27 additions & 2 deletions src/Domain/Services/SampleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,26 @@ public class SampleService : ISampleService
private readonly IRepository<SampleEntity> _repository;
private readonly IMapper _mapper;

private readonly ICacheManager _cacheManager;

public SampleService(IRepository<SampleEntity> repository,
IMapper mapper)
IMapper mapper,
ICacheManager cacheManager)
{
_repository = repository;
_mapper = mapper;
_cacheManager = cacheManager;
}

public async Task<GetSampleResponseModel> GetSampleAsync(Guid id, CancellationToken cancellationToken = default)
{
var cachedSample = await _cacheManager.GetAsync<SampleEntity>($"Sample_{id}");

if (cachedSample is not null)
{
return _mapper.Map<GetSampleResponseModel>(cachedSample);
}

var entity = await _repository.GetByIdAsync(id, cancellationToken) ?? throw new DomainException($"Sample with ID {id} not found.");

return _mapper.Map<GetSampleResponseModel>(entity);
Expand Down Expand Up @@ -66,15 +77,24 @@ public async Task<CreateSampleResponseModel> CreateSampleAsync(CreateSampleReque
{
var entity = _mapper.Map<SampleEntity>(request);
var createdEntity = await _repository.AddAsync(entity, cancellationToken);

await _repository.SaveChangesAsync(cancellationToken);

await _cacheManager.SetAsync($"Sample_{createdEntity.Id}", createdEntity);

return _mapper.Map<CreateSampleResponseModel>(createdEntity);
}

public async Task<UpdateSampleResponseModel> UpdateSampleAsync(UpdateSampleRequestModel request, CancellationToken cancellationToken = default)
{
var entity = _mapper.Map<SampleEntity>(request);

var updatedEntity = _repository.Update(entity);

await _repository.SaveChangesAsync(cancellationToken);

await _cacheManager.SetAsync($"Sample_{updatedEntity.Id}", updatedEntity);

return _mapper.Map<UpdateSampleResponseModel>(updatedEntity);
}

Expand All @@ -84,6 +104,11 @@ public async Task<bool> DeleteSampleAsync(Guid id, CancellationToken cancellatio
if (entity == null) return false;

_repository.Remove(entity);
return true && await _repository.SaveChangesAsync(cancellationToken) > 0;

var result = await _repository.SaveChangesAsync(cancellationToken);

await _cacheManager.RemoveAsync($"Sample_{id}");

return result > 0;
}
}
84 changes: 84 additions & 0 deletions src/Infra/Cache/CacheManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System.Text.Json;
using Domain.Interfaces;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;

namespace Infra.Cache;

public class CacheManagerOptions
{
public bool UseDistributedCache { get; set; } = true;
public TimeSpan MemoryCacheDuration { get; set; } = TimeSpan.FromMinutes(2);
public TimeSpan DistributedCacheDuration { get; set; } = TimeSpan.FromMinutes(10);
public JsonSerializerOptions? JsonOptions { get; set; }
}

public class CacheManager: ICacheManager
{
private readonly IMemoryCache _memoryCache;
private readonly IDistributedCache _distributedCache;
private readonly CacheManagerOptions _options;

public CacheManager(
IMemoryCache memoryCache,
IDistributedCache distributedCache,
IOptions<CacheManagerOptions> options)
{
_memoryCache = memoryCache;
_distributedCache = distributedCache;
_options = options.Value;
}

public async Task<T?> GetAsync<T>(string key)
{
if (_memoryCache.TryGetValue(key, out T? value))
return value;

if(!_options.UseDistributedCache)
return default;

var serialized = await _distributedCache.GetStringAsync(key);
if (serialized is not null)
{
value = JsonSerializer.Deserialize<T>(serialized, _options.JsonOptions)!;
_memoryCache.Set(key, value, _options.MemoryCacheDuration);
return value;
}

return default;
}

public async Task RemoveAsync(string key)
{
_memoryCache.Remove(key);

if (_options.UseDistributedCache)
await _distributedCache.RemoveAsync(key);
}

public async Task SetAsync<T>(string key, T value)
{
this.SetMemory(key, value);

if (_options.UseDistributedCache)
await this.SetDistributedAsync(key, value);
}

private void SetMemory<T>(string key, T value, TimeSpan? duration = null)
{
_memoryCache.Set(key, value, duration ?? _options.MemoryCacheDuration);
}

private Task SetDistributedAsync<T>(string key, T value, TimeSpan? duration = null)
{
var serialized = JsonSerializer.Serialize(value, _options.JsonOptions);
return _distributedCache.SetStringAsync(
key,
serialized,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = duration ?? _options.DistributedCacheDuration
});
}
}