Томашайтис Павел Лаб. 3 Группа 6513#113
Conversation
…но использование собственного балансировщика нагрузки
…жность публикации сообщений в брокер. Добавлена работа с объектным хранилищем S3 через Localstack.
…для последней версии пакета Localstack.
| /// <param name="logger"></param> | ||
| /// <param name="client"></param> | ||
| /// <param name="configuration"></param> | ||
| public class SnsPublisherService<T>(ILogger<SnsPublisherService<T>> logger, IAmazonSimpleNotificationService client, IConfiguration configuration) : IPublisherService<T> |
There was a problem hiding this comment.
Если честно, то тут можно было бы обойтись без дженерика
| ?? throw new KeyNotFoundException("SNS topic link was not found in configuration"); | ||
|
|
||
| /// <inheritdoc/> | ||
| public async Task<bool> SendMessage(int id, T entity, CancellationToken cancellationToken) |
There was a problem hiding this comment.
Ведь тут просто можно использовать object entity
Какого-то случая контрвариативности у тебя нет, ведь в di регистрируется только один экземпляр службы для Course
И каких-либо ограничений на T не накладывается
There was a problem hiding this comment.
Но в целом, как некоторое предвосхищение потенциального расширения функционала сервиса, если он, например, начнет заниматься генерацией контрактов разных типов, это вполне имеет право на существование.
Так что давай оставим все как есть
| var apiServiceConfig = builder.Configuration.GetSection("ApiService"); | ||
| var ports = apiServiceConfig.GetSection("Ports").Get<List<int>>() ?? []; | ||
|
|
||
| // Read configuration for Api Gateway | ||
| var apiGatewayConfig = builder.Configuration.GetSection("ApiGateway"); | ||
| var gatewayPort = apiGatewayConfig.GetValue<int>("Port"); | ||
|
|
||
| // Read configuration for AWS | ||
| var awsConfig = builder.Configuration.GetSection("AWS"); | ||
| var accessKey = awsConfig.GetValue<string>("AccessKeyId") ?? "none"; | ||
| var secretKey = awsConfig.GetValue<string>("SecretAccessKey") ?? "none"; | ||
| var region = awsConfig.GetValue<string>("Region") ?? "none"; | ||
|
|
||
| // Read configuration for AWS Resources | ||
| var awsResourcesConfig = awsConfig.GetSection("Resources"); | ||
| var topicName = awsResourcesConfig.GetValue<string>("TopicName") ?? "none"; | ||
| var bucketName = awsResourcesConfig.GetValue<string>("BucketName") ?? "none"; | ||
| var snsTopicArn = awsResourcesConfig.GetValue<string>("SNSTopicArn") ?? "none"; | ||
| var snsEndpointUrl = awsResourcesConfig.GetValue<string>("SNSEndpointURL") ?? "none"; | ||
|
|
||
| // Read configuration for Localstack, S3, SNS | ||
| var localStackServiceUrl = builder.Configuration.GetSection("LocalStack").GetValue<string>("ServiceURL") ?? "none"; | ||
| var s3ServiceUrl = builder.Configuration.GetSection("S3").GetValue<string>("ServiceURL") ?? "none"; | ||
| var snsServiceUrl = builder.Configuration.GetSection("SNS").GetValue<string>("ServiceURL") ?? "none"; |
There was a problem hiding this comment.
Отчасти из-за этого я и рекомендовал пользоваться сloud formation
Поскольку я не навязываю его использование, можно оставить и так
Но с сloud formation было бы меньше кода
| var localstack = builder.AddContainer("localstack", "localstack/localstack:3.8.0") | ||
| .WithEndpoint(port: 4566, targetPort: 4566, name: "localstack", scheme: "http") | ||
| .WithEnvironment("SERVICES", "sns,s3") | ||
| .WithEnvironment("AWS_ACCESS_KEY_ID", accessKey) | ||
| .WithEnvironment("AWS_SECRET_ACCESS_KEY", secretKey) | ||
| .WithEnvironment("AWS_DEFAULT_REGION", region) | ||
| .WithEnvironment("SKIP_SIGNATURE_VALIDATION", "1") | ||
| .WithContainerRuntimeArgs( | ||
| "--add-host", "host.docker.internal:host-gateway" | ||
| ); |
There was a problem hiding this comment.
А вот это уже надо править - у aspire есть библиотека для хостинга localstack
| var localstackInit = builder.AddContainer("localstack-init", "amazon/aws-cli") | ||
| .WithArgs( | ||
| $"--endpoint-url={localStackServiceUrl}", | ||
| "sns", "create-topic", | ||
| "--name", topicName, | ||
| "--region", region | ||
| ) | ||
| .WithEnvironment("AWS_ACCESS_KEY_ID", accessKey) | ||
| .WithEnvironment("AWS_SECRET_ACCESS_KEY", secretKey) | ||
| .WithEnvironment("AWS_DEFAULT_REGION", region) | ||
| .WaitFor(localstack); |
There was a problem hiding this comment.
Помимо того, что там будет телеметрия, не придется вручную настраивать локалстак через поднятие контейнера с cli
| <ItemGroup> | ||
| <PackageReference Include="Aspire.Hosting.AWS" Version="13.0.0" /> | ||
| <PackageReference Include="Aspire.Hosting.Redis" Version="13.1.1" /> | ||
| <PackageReference Include="LocalStack.Aspire.Hosting" Version="13.1.0" /> |
There was a problem hiding this comment.
Загадочно - нужная библиотека у тебя добавлена в проект, но ты ей не пользуешься
| var configuration = builder.Configuration; | ||
| var region = configuration["AWS:Region"] ?? throw new KeyNotFoundException("AWS region was not found in configuration"); | ||
| var accessKey = configuration["AWS:AccessKeyId"] ?? throw new KeyNotFoundException("AWS access key ID link was not found in configuration"); | ||
| var secretKey = configuration["AWS:SecretAccessKey"] ?? throw new KeyNotFoundException("AWS secret access key was not found in configuration"); | ||
| var s3Url = configuration["S3:ServiceURL"] ?? throw new KeyNotFoundException("S3 service URL was not found in configuration"); | ||
| var snsUrl = configuration["SNS:ServiceURL"] ?? throw new KeyNotFoundException("SNS service URL was not found in configuration"); |
There was a problem hiding this comment.
По идее, у тебя есть клиенская библиотека localstack, так что можно упростить регистрацию служб через
builder.Services.AddLocalStack(builder.Configuration);, если параметры подключения в конфигурации прописаны в ожидаемом для localstack формате
| builder.Services.AddSingleton<IAmazonS3>( | ||
| new AmazonS3Client(accessKey, secretKey, new AmazonS3Config | ||
| { | ||
| ServiceURL = s3Url, | ||
| UseHttp = true, | ||
| AuthenticationRegion = region | ||
| }) | ||
| ); | ||
| builder.Services.AddSingleton<IAmazonSimpleNotificationService>( | ||
| new AmazonSimpleNotificationServiceClient(accessKey, secretKey, new AmazonSimpleNotificationServiceConfig | ||
| { | ||
| ServiceURL = snsUrl, | ||
| UseHttp = true, | ||
| AuthenticationRegion = region | ||
| }) | ||
| ); |
There was a problem hiding this comment.
У тебя, вроде бы, добавлены все необходимые пакеты, чтобы не издеваться над собой и просто написать:
builder.Services.AddAwsService<IAmazonS3>();
builder.Services.AddAwsService<IAmazonSimpleNotificationService>();Все параметры подтянутся из localstack
There was a problem hiding this comment.
Кстати, раз уж ты живешь на 18 студии и 10 дотнете, то можно перейти на slnx
dotnet sln CourseManagement.sln migrate
Только не забудь удалить старый sln
|
Изменил структуру проекта, добавил cloud formation. |
ФИО: Томашайтис Павел
Номер группы: 6513
Номер лабораторной: 3
Номер варианта: 52
Краткое описание предметной области: Учебный курс
Краткое описание добавленных фич: