首頁 C# 使用Microservice架構設計( dotnet 6.0 )
文章
Cancel

C# 使用Microservice架構設計( dotnet 6.0 )

前言

架構圖

理想中的架構長的像這樣

User可以透過作為Geteway用途API,去訪問到其他API

Desktop View

照著這篇文章實作以後,達成的結構會像這樣

Desktop View

建立ASP.NET Core Web API (1/2)

新增專案,其名為CompanyManagement

建立方式如下

Desktop View Desktop View Desktop View Desktop View

新增CompanyModel.cs

建立方式如下

Desktop View

1
2
3
4
5
6
7
8
9
10
namespace CompanyManagement
{
    public class CompanyModel
    {
        public int CompanyID { get; set; }
        public string CompanyName { get; set; }
        public string CompanyClass { get; set; }
        public DateTime DateofJoining { get; set; }
    }
}

新增CompanyServiceController.cs

建立方式如下

Desktop View Desktop View Desktop View

設定 API Controller

API Controller的function如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using Microsoft.AspNetCore.Mvc;
namespace CompanyManagement.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CompanyServiceController : ControllerBase
    {
        // GET: api/<StudentAdmissionController>
        [HttpGet]
        public IEnumerable<CompanyModel> Get()
        {
            CompanyModel admissionobj1 = new CompanyModel();
            CompanyModel admissionobj2 = new CompanyModel();
            admissionobj1.CompanyID = 1;
            admissionobj1.CompanyName = "HI";
            admissionobj1.CompanyClass = "X";
            admissionobj1.DateofJoining = DateTime.Now;
            admissionobj2.CompanyID = 2;
            admissionobj2.CompanyName = "Jay";
            admissionobj2.CompanyClass = "V";
            admissionobj2.DateofJoining = DateTime.Now;
            List<CompanyModel> listofobj = new List<CompanyModel>
            {
                admissionobj1,
                admissionobj2
            };
            return listofobj;
        }
    }
}

執行API顯示結果

Desktop View Desktop View

建立ASP.NET Core Web API (2/2)

新增專案,其名為EmpDetail

新增專案

Desktop View Desktop View Desktop View Desktop View ### 新增EmpDetail.cs Desktop View

1
2
3
4
5
6
7
8
9
 namespace EmpDetail
{
    public class EmpModel
    {
        public int EmpID { get; set; }
        public string EmpName { get; set; }
        public double AttendencePercentage { get; set; }
    }
}

新增EmpServiceController.cs

Desktop View Desktop View Desktop View

設定 API Controller

API Controller的function如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using Microsoft.AspNetCore.Mvc;
namespace EmpDetail.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmpServiceController : ControllerBase
    {

        [HttpGet]
        public IEnumerable<EmpModel> Get()
        {
            EmpModel attendanceObj1 = new EmpModel();
            EmpModel attendanceObj2 = new EmpModel();
            attendanceObj1.EmpID = 1;
            attendanceObj1.EmpName = "Adam";
            attendanceObj1.AttendencePercentage = 83.02;
            attendanceObj2.EmpID = 2;
            attendanceObj2.EmpName = "Brad";
            attendanceObj2.AttendencePercentage = 71.02;
            List<EmpModel> listObj = new List<EmpModel>
            {
                attendanceObj1,
                attendanceObj2
            };
            return listObj;
        }
    }
}

執行API顯示結果

Desktop View Desktop View

設定「同時啟動多個專案」

Desktop View Desktop View Desktop View Desktop View

建立專案「APIGeteway」

Desktop View Desktop View Desktop View Desktop View Desktop View

在APIGeteway專案中,安裝Ocelot

Desktop View

1
NuGet\Install-Package Ocelot -Version 18.0.0

新增Ocelot.json

Desktop View Desktop View

設定Ocelot.json

Ocelot.json的內容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/CompanyService",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 7185
        }
      ],
      "UpstreamPathTemplate": "/apigateway/CompanyAPI",
      "UpstreamHttpMethod": [ "GET", "PUT", "POST" ]
    },
    {
      "DownstreamPathTemplate": "/api/EmpService",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 7252
        }
      ],
      "UpstreamPathTemplate": "/apigateway/EmpAPI",
      "UpstreamHttpMethod": [ "GET", "PUT", "POST" ]
    }
  ]
}

設定啟動時,根據JSON載入設定

Desktop View

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(options => {
    options.AddPolicy("CORSPolicy", builder => builder.AllowAnyMethod().AllowAnyHeader().AllowCredentials().SetIsOriginAllowed((hosts) => true));
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Configuration.AddJsonFile("Ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot(builder.Configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseCors("CORSPolicy");
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
await app.UseOcelot();
app.Run();

設定多專案同時啟動

Desktop View

Ocelot.json設定對照

Desktop View Desktop View

Microservice架構DEMO成功的顯示結果

執行專案

可以從APIGeteway的網址調用到其他專案的API

Desktop View

GitHub

https://github.com/digamana/MicroservicesRepo.git

本文由作者按照 CC BY 4.0 進行授權