.NET 如何搭建一个完整的微服务应用

在 .NET 中搭建微服务应用需遵循模块化、独立部署和分布式治理等核心原则。以下是结合最新实践(.NET 8 和 Docker/Kubernetes)的完整流程:


⚙️ 一、环境准备

  1. 安装 .NET SDK

    • 下载 .NET 8 SDK(跨平台支持 Win/Linux/macOS)
    • 验证安装:dotnet --version
  2. 安装 Docker

    • 用于容器化微服务:Docker Desktop
    • 验证安装:docker --version

🧩 二、创建基础微服务(以用户服务为例)

步骤:
  1. 创建 Web API 项目

    dotnet new webapi -n UserService -f net8.0 --no-https
    cd UserService
    
  2. 实现业务逻辑
    修改 Controllers/UsersController.cs

    [ApiController]
    [Route("api/[controller]")]
    public class UsersController : ControllerBase
    {
         
         
        [HttpGet("{id}")]
        public IActionResult GetUser(int id)
        {
         
         
            return Ok(new {
         
          Id = id, Name = "John Doe", Email = "[email protected]" });
        }
    }
    
  3. 运行服务

    dotnet run --urls http://localhost:5001
    
    • 访问 http://localhost:5001/api/users/1 测试

📦 三、容器化微服务

  1. 添加 Dockerfile(项目根目录)

    # 构建阶段
    FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
    WORKDIR /src
    COPY UserService.csproj .
    RUN dotnet restore
    COPY . .
    RUN dotnet publish -c Release -o /app
    
    # 运行阶段
    FROM mcr.microsoft.com/dotnet/aspnet:8.0
    WORKDIR /app
    COPY --from=build /app .
    ENTRYPOINT ["dotnet", "UserService.dll"]
    
  2. 构建并运行容器

    docker build -t user-service .
    docker run -d -p 5001:80 --name user-container user-service
    
    • 访问 http://localhost:5001/api/users/1

🌐 四、构建多服务架构

  1. 创建订单服务(同用户服务步骤)

    dotnet new webapi -n OrderService -f net8.0 --no-https
    
  2. 添加 API 网关(Ocelot)

    • 创建网关项目:
      dotnet new webapi -n ApiGateway
      cd ApiGateway
      dotnet add package Ocelot
      
    • 配置 appsettings.json
      {
             
             
        "Routes": [
          {
             
             
            "DownstreamPathTemplate": "/api/users/{id}",
            "DownstreamHostAndPorts": [ {
             
              "Host": "user-service"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值