add Redis service

This commit is contained in:
m.zargarov 2024-12-01 19:33:52 +04:00
parent c34926e1ec
commit 9c0aad605c
4 changed files with 54 additions and 8 deletions

View File

@ -8,6 +8,7 @@ using FluentValidation.AspNetCore;
using Cloud.Validation;
using StackExchange.Redis;
using Cloud.Services;
using Cloud.Services.Cache;
var builder = WebApplication.CreateBuilder(args);
@ -20,6 +21,8 @@ builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
return ConnectionMultiplexer.Connect(configuration);
});
builder.Services.AddSingleton<IRedisCacheService, RedisCacheService>();
//Kafka producer service
builder.Services.AddSingleton<ProducerService, ProducerService>();

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Cloud.Services.Cache
{
public interface IRedisCacheService
{
Task SetCacheAsync<T>(string key, T value, TimeSpan? expiry = null);
Task<T?> GetCacheAsync<T>(string key);
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StackExchange.Redis;
using System.Text.Json;
namespace Cloud.Services.Cache
{
public class RedisCacheService : IRedisCacheService
{
private readonly IConnectionMultiplexer _connectionMultiplexer;
public RedisCacheService(IConnectionMultiplexer connectionMultiplexer)
{
_connectionMultiplexer = connectionMultiplexer;
}
public async Task SetCacheAsync<T>(string key, T value, TimeSpan? expiry = null)
{
var database = _connectionMultiplexer.GetDatabase();
var serializedValue = JsonSerializer.Serialize(value);
await database.StringSetAsync(key, serializedValue, expiry);
}
public async Task<T?> GetCacheAsync<T>(string key)
{
var database = _connectionMultiplexer.GetDatabase();
var value = await database.StringGetAsync(key);
if (value.IsNullOrEmpty)
return default;
return JsonSerializer.Deserialize<T>(value);
}
}
}

View File

@ -108,11 +108,4 @@ volumes:
postgres_data:
driver: local
cloud-redis:
driver: local
zookeeper:
image: confluentinc/cp-zookeeper:7.4.0
environment:
ZOOKEEPER_CLIENT_PORT: 2181
ZOOKEEPER_TICK_TIME: 2000
ports:
- 2181:2181
driver: local