fix: есть контакт! между облаком и кафкой

This commit is contained in:
mfnefd 2024-12-04 06:27:39 +04:00
parent 2e20e9d7cc
commit 739d434f53
9 changed files with 56 additions and 22 deletions

2
.env
View File

@ -1,4 +1,4 @@
POSTGRES_USER="postgres"
POSTGRES_PASSWORD="12345"
POSTGRES_DB="main_database"
DB_CONNECTION_STRING="Host=postgres:5438;Database=${POSTGRES_DB};Username=${POSTGRES_USER};Password=${POSTGRES_PASSWORD}"
DB_CONNECTION_STRING="Host=postgres:5432;Database=${POSTGRES_DB};Username=${POSTGRES_USER};Password=${POSTGRES_PASSWORD}"

View File

@ -28,6 +28,7 @@ namespace Cloud.Controllers
try
{
var greenhouses = _greenhouseService.GetAll(farmId);
if (greenhouses == null) return NotFound("Greenhouses is not found");
return Ok(greenhouses);
}
catch (Exception ex)

View File

@ -10,7 +10,7 @@ RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /
USER appuser
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
ARG configuration=Debug
ARG configuration=Development
WORKDIR /src
COPY ["Cloud.csproj", "."]
RUN dotnet restore "./Cloud.csproj"
@ -19,7 +19,7 @@ WORKDIR "/src/."
RUN dotnet build "./Cloud.csproj" -c $configuration -o /app/build
FROM build AS publish
ARG configuration=Release
ARG configuration=Development
RUN dotnet publish "./Cloud.csproj" -c $configuration -o /app/publish /p:UseAppHost=false
FROM base AS final

View File

@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore;
namespace Cloud.Middlewares;
public static class DatabaseMiddleware
{
public static void AddDbConnectionService(this IServiceCollection services)
{
string connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING")
?? "Host=localhost;Port=5438;Database=main_database;Username=postgres;Password=12345";
services.AddDbContext<ApplicationContext>(options =>
options.UseNpgsql(connectionString));
}
public static void MigrateDb(this IApplicationBuilder app)
{
try
{
using var scope = app.ApplicationServices.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationContext>();
context.Database.Migrate();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

View File

@ -15,6 +15,7 @@ using Cloud.Services.Domain;
using Cloud.Services.Cache;
using Cloud.Support;
using System.Text.RegularExpressions;
using Cloud.Middlewares;
var builder = WebApplication.CreateBuilder(args);
@ -49,15 +50,8 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
};
});
string connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING")
?? "Host=localhost;Port=5438;Database=main_database;Username=postgres;Password=12345";
string dbUrl = "http://" + Regex.Match(connectionString, @"(?<=Host=)([^;]+)").Groups[1].Value;
await NetworkSupport.CheckConnectionAsync(dbUrl);
builder.Services.AddDbContext<ApplicationContext>(options =>
options.UseNpgsql(connectionString));
// Настройка подключения к БД
builder.Services.AddDbConnectionService();
// Настройка CORS
string frontUrl = Environment.GetEnvironmentVariable("FRONT_URL") ?? "http://localhost:3000";
builder.Services.AddCors(options =>
@ -113,6 +107,7 @@ var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
Console.WriteLine("Swagger enabled");
app.UseSwagger();
app.UseSwaggerUI(c =>
{
@ -126,6 +121,9 @@ app.UseHttpsRedirection();
// Включение CORS
app.UseCors("AllowFrontendLocalhost");
// Применение миграций
app.MigrateDb();
app.UseAuthentication();
app.UseAuthorization();

View File

@ -13,7 +13,8 @@ namespace Cloud.Services.Broker.Implement.Kafka
public KafkaConsumer(IConfiguration config)
{
_config = config;
ChangeBrokerIp(_config["Kafka:BootstrapServers"]);
Console.WriteLine($"KafkaConsumer created. IP:" + _config["KAFKA_URL"]);
ChangeBrokerIp(_config["KAFKA_URL"]);
}
public IEnumerable<T>? WaitMessages<T>(string topic)

View File

@ -1,3 +1,4 @@
using System.Text.Json;
using Cloud.Services.Broker.Support;
using Confluent.Kafka;
@ -5,18 +6,19 @@ namespace Cloud.Services.Broker.Implement.Kafka
{
public class KafkaProducer : IBrokerProducer
{
private IProducer<Guid, Command> _producer;
private IProducer<string, string> _producer;
private readonly IConfiguration _config;
public KafkaProducer(IConfiguration configuration)
{
_config = configuration;
ChangeBrokerIp(_config["Kafka:BootstrapServers"]);
Console.WriteLine($"KafkaConsumer created. IP:" + _config["KAFKA_URL"]);
ChangeBrokerIp(_config["KAFKA_URL"]);
}
public async Task ProduceAsync(string topic, Command command)
{
var message = new Message<Guid, Command> { Key = Guid.NewGuid(), Value = command };
var commandSerialized = JsonSerializer.Serialize(command);
var message = new Message<string, string> { Key = Guid.NewGuid().ToString(), Value = commandSerialized };
//Produce the Message
await _producer.ProduceAsync(topic, message);
@ -30,7 +32,7 @@ namespace Cloud.Services.Broker.Implement.Kafka
};
//Build the Producer
_producer = new ProducerBuilder<Guid, Command>(producerConfig).Build();
_producer = new ProducerBuilder<string, string>(producerConfig).Build();
}
}
}

View File

@ -47,13 +47,13 @@ public class GreenhouseService : IGreenhouseService
public async Task<IEnumerable<GreenhouseInfo>?> GetAll(int farmId)
{
await _changeBrokerIp(farmId);
// await _changeBrokerIp(farmId);
return _brokerService.WaitMessages<GreenhouseInfo>("data");
}
public async Task<GreenhouseInfo?> GetGreenhouseInfo(int id, int farmId)
{
await _changeBrokerIp(farmId);
// await _changeBrokerIp(farmId);
var infos = _brokerService.WaitMessages<GreenhouseInfo>("data");
return infos?.FirstOrDefault(x => x.Id == id);
}

View File

@ -9,14 +9,16 @@ networks:
services:
cloud:
networks:
- vpn
build: ./Cloud/
ports:
- "5124:5124"
environment:
ASPNETCORE_ENVIRONMENT: Development
DB_CONNECTION_STRING: ${DB_CONNECTION_STRING}
REDDIS_URL: redis:6379
# На всякий случай, если будет больно
# KAFKA_URL: kafka:9092
KAFKA_URL: kafka:29092
# Добавить, когда будет фронт!
# FRONT_URL: front:3000
depends_on: