在 .NET 中部署和维护的 20 个基本技巧

作者:微信公众号:【架构师老卢】
11-10 19:40
82

本文演示了 20 个可行的技巧,以增强开发流程并确保可靠、可扩展的解决方案。

1. 利用 Docker 进行一致的部署

使用 Dockerfile 为您的 .NET 应用程序创建一致的环境:

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["MyApp/MyApp.csproj", "MyApp/"]
RUN dotnet restore "MyApp/MyApp.csproj"
COPY . .
WORKDIR "/src/MyApp"
RUN dotnet build "MyApp.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyApp.dll"]

2. 实施持续集成 (CI)

用于生成和测试 .NET 应用程序的 GitHub Actions 工作流示例:

name: .NET Build and Test
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Setup .NET
      uses: actions/setup-dotnet@v1
      with:
        dotnet-version: '8.0'
    - name: Restore dependencies
      run: dotnet restore
    - name: Build
      run: dotnet build --no-restore
    - name: Test
      run: dotnet test --no-build

3. 持续部署 (CD) 策略

扩展 CI 管道以包括到 Azure 应用服务的部署:

- name: Deploy to Azure
  run: az webapp deploy --name <app-name> --resource-group <resource-group> --src-path ./MyApp/bin/Release/net8/publish/

4. 数据库迁移管理

使用 Entity Framework Core 自动迁移:

dotnet ef migrations add InitialCreate  
dotnet ef database update

5. 使用 Application Insights 进行监控和遥测

在 中配置 Application Insights :Program.cs

builder.Services.AddApplicationInsightsTelemetry("YOUR_INSTRUMENTATION_KEY");

6. 运行状况检查和负载均衡

在您的应用程序中实施运行状况检查:

builder.Services.AddHealthChecks();  // Add this in your Program.cs  
  
app.MapHealthChecks("/health");  // Map health checks endpoin

t

7. 自动数据库备份

使用 SQL Server 代理或 Azure 中的脚本自动备份:

builder.Services.AddHealthChecks();  // Add this in your Program.cs

app.MapHealthChecks("/health");  // Map health checks endpoint

8. 安全最佳实践

在 中强制执行 HTTPS 重定向 :Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
{  
    app.UseHttpsRedirection();  // Redirect HTTP to HTTPS  
}

9. 实施 API 版本控制

管理不同版本的 API 以确保向后兼容性:

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddApiVersioning(options => {  
        options.DefaultApiVersion = new ApiVersion(1, 0);  
        options.AssumeDefaultVersionWhenUnspecified = true;  
        options.ReportApiVersions = true;  
    });  
}

10. 文档和变更管理

使用 Swagger 等工具更新 API 文档:

builder.Services.AddSwaggerGen();  
app.UseSwagger();  
app.UseSwaggerUI(c => {  
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");  
});

11. 优化 Docker 镜像

通过多阶段构建和删除不必要的文件来最小化 Docker 镜像大小:

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["MyApp.csproj", "./"]
RUN dotnet restore "MyApp.csproj"

COPY . .
RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish --no-restore
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyApp.dll"]

12. 使用环境变量进行配置

通过环境变量管理设置和配置,以将敏感数据排除在代码之外:

public void ConfigureServices(IServiceCollection services)  
{  
    var mySetting = Environment.GetEnvironmentVariable("MY_SETTING");  
    // Use mySetting in your application  
}

13. 使用 Serilog 实现日志记录

设置 Serilog 以获得高级日志记录功能:

var logger = new LoggerConfiguration()  
    .ReadFrom.Configuration(configuration)  
    .Enrich.FromLogContext()  
    .WriteTo.Console()  
    .CreateLogger();  
  
builder.Logging.ClearProviders();  
builder.Logging.AddSerilog(logger);

14. 高效扩展应用程序

使用 Kubernetes 或可缩放的平台(如 Azure 应用服务)来管理应用程序缩放:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: myapp:latest

15. 使用加密保护数据

利用 .NET 中的数据保护 API 加密敏感数据:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection();
}

public class MyService
{
    private readonly IDataProtector _protector;
    public MyService(IDataProtectionProvider provider)
    {
        _protector = provider.CreateProtector("MyPurpose");
    }
    public string EncryptData(string input)
    {
        return _protector.Protect(input);
    }
    public string DecryptData(string encryptedData)
    {
        return _protector.Unprotect(encryptedData);
    }
}

16. 使用代码质量工具

实施 SonarQube 等代码质量工具以保持高标准的代码质量:

sonarqube:
  build:
    script:
      - dotnet sonarscanner begin /k:"project-key" /d:sonar.host.url="https://sonarqube.example.com"
      - dotnet build
      - dotnet sonarscanner end

17. 使用配置提供程序进行动态设置

利用 .NET 中的各种配置源动态管理设置:

var builder = WebApplication.CreateBuilder(args);  
builder.Configuration.AddJsonFile("appsettings.json");  
builder.Configuration.AddEnvironmentVariables();

18. 数据库连接弹性

使用 Entity Framework Core 实现连接复原能力:

services.AddDbContext<MyDbContext>(options =>  
    options.UseSqlServer(  
        configuration.GetConnectionString("MyDatabase"),  
        sqlServerOptionsAction: sqlOptions =>  
        {  
            sqlOptions.EnableRetryOnFailure(  
                maxRetryCount: 5,  
                maxRetryDelay: TimeSpan.FromSeconds(30),  
                errorNumbersToAdd: null);  
        }));

19. 结构化日志记录

使用 Serilog 实现结构化日志记录以增强日志的可读性和实用性:

Log.Logger = new LoggerConfiguration()  
    .Enrich.FromLogContext()  
    .WriteTo.Console(new RenderedCompactJsonFormatter())  
    .CreateLogger();

20. 高级应用程序指标

使用 Prometheus 和 Grafana 对应用程序指标进行高级监控和可视化:

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddPrometheusMetrics();  
}  
  
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
{  
    app.UsePrometheusServer();  
    app.UsePrometheusRequestMiddleware();  
}
相关留言评论
昵称:
邮箱:
阅读排行