Skip to content

Commit

Permalink
加入 MassTransit 專案
Browse files Browse the repository at this point in the history
  • Loading branch information
yaochangyu committed Oct 13, 2024
1 parent 02ef0ff commit 5892a44
Show file tree
Hide file tree
Showing 12 changed files with 224 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
<PackageReference Include="MassTransit.RabbitMQ" Version="8.2.5" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />

</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@Lab.MassTransit.WebAPI_HostAddress = http://localhost:5089

GET {{Lab.MassTransit.WebAPI_HostAddress}}/weatherforecast/
Accept: application/json

###
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Lab.MassTransit.WebAPI.Order;

// 訂單請求
public class CreateOrderRequest
{
public decimal TotalAmount { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Lab.MassTransit.WebAPI;

// 訂單已建立
public class OrderCreated
{
public Guid OrderId { get; set; }

public DateTime CreatedAt { get; set; }

public decimal TotalAmount { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using MassTransit;

namespace Lab.MassTransit.WebAPI;

public class OrderCreatedConsumer : IConsumer<OrderCreated>
{
public Task Consume(ConsumeContext<OrderCreated> context)
{
Console.WriteLine($"Order created: {context.Message.OrderId}, Total Amount: {context.Message.TotalAmount}");
return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using MassTransit;
using Microsoft.AspNetCore.Mvc;

namespace Lab.MassTransit.WebAPI.Order;

[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
private readonly IPublishEndpoint _publishEndpoint;
public OrdersController(IPublishEndpoint publishEndpoint)
{
this._publishEndpoint = publishEndpoint;
}

[HttpPost]
public async Task<ActionResult> CreateOrder([FromBody] CreateOrderRequest request)
{
if (request == null)
{
return this.BadRequest("Invalid order data");
}

var orderCreatedEvent = new OrderCreated
{
OrderId = Guid.NewGuid(),
CreatedAt = DateTime.UtcNow,
TotalAmount = request.TotalAmount
};

// 生產者,發布 OrderCreated 事件
await this._publishEndpoint.Publish(orderCreatedEvent);

return this.Ok($"Order created with ID: {orderCreatedEvent.OrderId}");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using Lab.MassTransit.WebAPI;
using MassTransit;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddMassTransit(x =>
{
// 註冊消費者
x.AddConsumer<OrderCreatedConsumer>();

// 配置 MassTransit 使用 RabbitMQ
x.UsingRabbitMq((context, config) =>
{
config.Host("localhost", "/", h =>
{
h.Username("guest");
h.Password("guest");
});
// 註冊消費者
config.ReceiveEndpoint("order/created/event", e => { e.ConfigureConsumer<OrderCreatedConsumer>(context); });
});
});
builder.Services.AddControllers();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

// 使用中介軟體和路由
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

app.UseHttpsRedirection();

app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:65484",
"sslPort": 44345
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5089",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7293;http://localhost:5089",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
21 changes: 21 additions & 0 deletions Event Bus/MassTransit/Lab.MassTransit/Lab.MassTransit.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lab.MassTransit.WebAPI", "Lab.MassTransit.WebAPI\Lab.MassTransit.WebAPI.csproj", "{626813B6-52DA-479B-A50B-94E364E63F3C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{34BE7295-45E2-45CE-997C-3A9F533583A5}"
ProjectSection(SolutionItems) = preProject
docker-compose.yml = docker-compose.yml
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{626813B6-52DA-479B-A50B-94E364E63F3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{626813B6-52DA-479B-A50B-94E364E63F3C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{626813B6-52DA-479B-A50B-94E364E63F3C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{626813B6-52DA-479B-A50B-94E364E63F3C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
11 changes: 11 additions & 0 deletions Event Bus/MassTransit/Lab.MassTransit/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
version: '3.8'
services:
rabbitmq:
container_name: rabbitmq.3
image: "rabbitmq:3-management"
ports:
- "5672:5672" # RabbitMQ 主要連接埠
- "15672:15672" # 管理介面連接埠
environment:
RABBITMQ_DEFAULT_USER: guest
RABBITMQ_DEFAULT_PASS: guest

0 comments on commit 5892a44

Please sign in to comment.