fixed rabbit mq in web api events task

This commit is contained in:
Egor 2022-08-28 05:08:04 +03:00
parent f9d32f8b71
commit 4e4a0b442c
11 changed files with 112 additions and 33 deletions

View file

@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.2.32630.192 VisualStudioVersion = 17.2.32630.192
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAPIEventsTask", "WebAPIEventsTask\WebAPIEventsTask.csproj", "{E9A9B7F9-A548-45CD-B9BA-C7BC45A3F98C}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebAPIEventsTask", "WebAPIEventsTask\WebAPIEventsTask.csproj", "{E9A9B7F9-A548-45CD-B9BA-C7BC45A3F98C}"
EndProject
Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{B3774CDE-2560-4C27-81F9-688296719AFE}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,6 +17,10 @@ Global
{E9A9B7F9-A548-45CD-B9BA-C7BC45A3F98C}.Debug|Any CPU.Build.0 = Debug|Any CPU {E9A9B7F9-A548-45CD-B9BA-C7BC45A3F98C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E9A9B7F9-A548-45CD-B9BA-C7BC45A3F98C}.Release|Any CPU.ActiveCfg = Release|Any CPU {E9A9B7F9-A548-45CD-B9BA-C7BC45A3F98C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E9A9B7F9-A548-45CD-B9BA-C7BC45A3F98C}.Release|Any CPU.Build.0 = Release|Any CPU {E9A9B7F9-A548-45CD-B9BA-C7BC45A3F98C}.Release|Any CPU.Build.0 = Release|Any CPU
{B3774CDE-2560-4C27-81F9-688296719AFE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3774CDE-2560-4C27-81F9-688296719AFE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3774CDE-2560-4C27-81F9-688296719AFE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3774CDE-2560-4C27-81F9-688296719AFE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View file

@ -1,7 +1,4 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
namespace WebAPIEventsTask.Controllers namespace WebAPIEventsTask.Controllers
{ {
@ -11,41 +8,26 @@ namespace WebAPIEventsTask.Controllers
{ {
private readonly ILogger<EventController> _logger; private readonly ILogger<EventController> _logger;
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
private static IModel rmqChannel; private readonly IMessageService _messageService;
private static readonly string QUEUE_NAME = "test-queue";
static EventController() public EventController(ILogger<EventController> logger, IConfiguration configuration, IMessageService messageService)
{
var connectionFactory = new ConnectionFactory { HostName = "localhost" };
var connection = connectionFactory.CreateConnection();
rmqChannel = connection.CreateModel();
}
public EventController(ILogger<EventController> logger, IConfiguration configuration)
{ {
_logger = logger; _logger = logger;
_configuration = configuration; _configuration = configuration;
rmqChannel.QueueDeclare(QUEUE_NAME, false, false, false); _messageService = messageService;
} }
[HttpPost("send")] [HttpPost("send")]
public IActionResult SendMessage(string msg) public IActionResult SendMessage(string msg)
{ {
rmqChannel.BasicPublish("", QUEUE_NAME, null, Encoding.UTF8.GetBytes(msg)); _messageService.SendMessage(msg);
return Ok(); return Ok();
} }
[HttpGet("receive")] [HttpGet("receive")]
public IActionResult ReceiveMessage() public IActionResult ReceiveMessage()
{ {
var consumer = new EventingBasicConsumer(rmqChannel); string? msg = _messageService.ReceiveMessage();
string? msg = null;
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
msg = Encoding.UTF8.GetString(body);
};
rmqChannel.BasicConsume(QUEUE_NAME, true, consumer);
return msg == null ? NotFound() : Ok(msg); return msg == null ? NotFound() : Ok(msg);
} }
} }

View file

@ -0,0 +1,8 @@
namespace WebAPIEventsTask
{
public interface IMessageService
{
public void SendMessage(string message);
public string? ReceiveMessage();
}
}

View file

@ -1,7 +1,9 @@
using WebAPIEventsTask;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
builder.Services.AddSingleton<IMessageService, RabbitMQService>();
builder.Services.AddControllers(); builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();

View file

@ -0,0 +1,42 @@
using RabbitMQ.Client;
using System.Text;
namespace WebAPIEventsTask
{
public class RabbitMQService : IMessageService
{
private readonly IConfiguration _configuration;
private readonly ConnectionFactory _connectionFactory;
private readonly IConnection _connection;
private readonly IModel _channel;
public RabbitMQService(IConfiguration configuration)
{
_configuration = configuration;
_connectionFactory = new() { Uri = new(_configuration.GetConnectionString("RabbitMQ")) };
_connection = _connectionFactory.CreateConnection();
_channel = _connection.CreateModel();
_channel.QueueDeclare(queue: "msg-queue",
durable: false,
exclusive: false,
autoDelete: false);
}
public string? ReceiveMessage()
{
var result = _channel.BasicGet("msg-queue", true);
if (result is null) return null;
var body = result.Body.ToArray();
var msg = Encoding.UTF8.GetString(body);
return msg;
}
public void SendMessage(string message)
{
var body = Encoding.UTF8.GetBytes(message);
_channel.BasicPublish(exchange: "",
routingKey: "msg-queue",
body: body);
}
}
}

View file

@ -1,7 +0,0 @@
namespace WebAPIEventsTask
{
public class Startup
{
}
}

View file

@ -6,6 +6,7 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>befb116a-f711-4f3f-9475-d96563d5378b</UserSecretsId> <UserSecretsId>befb116a-f711-4f3f-9475-d96563d5378b</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerComposeProjectPath>..\docker-compose.dcproj</DockerComposeProjectPath>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View file

@ -7,6 +7,6 @@
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStrings": { "ConnectionStrings": {
"RabbitMQ": "amqp://guest:guest@localhost:5672" "RabbitMQ": "amqp://guest:guest@rabbitmq:5672"
} }
} }

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" Sdk="Microsoft.Docker.Sdk">
<PropertyGroup Label="Globals">
<ProjectVersion>2.1</ProjectVersion>
<DockerTargetOS>Linux</DockerTargetOS>
<ProjectGuid>b3774cde-2560-4c27-81f9-688296719afe</ProjectGuid>
<DockerLaunchAction>LaunchBrowser</DockerLaunchAction>
<DockerServiceUrl>{Scheme}://localhost:{ServicePort}/swagger</DockerServiceUrl>
<DockerServiceName>webapieventstask</DockerServiceName>
</PropertyGroup>
<ItemGroup>
<None Include="docker-compose.override.yml">
<DependentUpon>docker-compose.yml</DependentUpon>
</None>
<None Include="docker-compose.yml" />
<None Include=".dockerignore" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,13 @@
version: '3.4'
services:
webapieventstask:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:443;http://+:80
ports:
- "80"
- "443"
volumes:
- ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
- ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro

View file

@ -0,0 +1,14 @@
version: '3.4'
services:
webapieventstask:
container_name: webapi
image: ${DOCKER_REGISTRY-}webapieventstask
build:
context: .
dockerfile: WebAPIEventsTask/Dockerfile
rabbitmq:
container_name: rabbitmq
image: rabbitmq
ports:
- 5672:5672