1. 程式人生 > >[翻譯] 使用 Serverless 和 .NET Core 構建飛速發展的架構

[翻譯] 使用 Serverless 和 .NET Core 構建飛速發展的架構

原文:Fast growing architectures with serverless and .NET Core
作者:Samuele Resca

Serverless 技術為開發人員提供了一種快速而獨立的方式將實現投入生產。這種技術在企業的技術棧中日益流行,自 2017 年以來,它一直是 ThoughtWorks 技術雷達的實驗級別的技術[譯註:技術雷達是 ThoughtWorks 每半年釋出的前沿技術解析]。

本篇文章的第一部分介紹了有關 Serverless 計算的基本概念。第二部分展示瞭如何構建 .NET Core 的 Lambda 函式,其中使用了 AWS 的 Serverless 框架。

Serverless 計算的好處

Serverless 技術是 FaaS(功能即服務)技術體系的一部分。隨著雲端計算的採用,這些技術變得越來越受歡迎。如今,serverless 實現被提升為雲端計算提供商的首選技術,無論是私有云還是公有云。

此外,典型的軟體服務和系統會通過在記憶體中保留大量資料並在複雜資料來源中寫入成批資料來完成操作。
然而一般而言,像 Serverless 一樣的 FaaS 技術旨在通過儘可能快地處理許多小請求和事件,來使我們的系統保持快速響應。Serverless 元件通常與執行它們的雲服務商所提供的事件緊密耦合:一個通知、一個佇列排程的事件或者一個來自 API 閘道器的請求,都被視為此元件中包含的一小部分計算的觸發器。這也就是雲服務商的定價系統基於請求數而不是基於計算時間的主要原因。

再者,serverless 元件通常在執行時間上有一些限制。與每種技術一樣,serverless 並不適合每一個解決方案和系統。但是事實上,它確實簡化了軟體工程師的一些工作,lambda 部署週期通常很快,開發人員只需要做少量工作就可以快速將新功能投入生產。此外,使用 serverless 技術構建元件意味著開發人員無需擔心擴充套件問題或故障,讓雲提供商去關心這些問題吧。

最後,我們還應該知道 serverless 函式是無狀態的。因此,基於此技術構建的每個系統都更加模組化和鬆耦合。

Serverless 的痛點

但是這種能力和敏捷性卻不是沒有代價的。首先,serverless 函式是在雲上執行的,它們通常由與雲提供商緊密耦合的事件觸發,因此除錯它們並不容易。這就是為什麼要使它的作用域保持儘可能小,並且始終將函式的核心邏輯與外部元件和事件分隔開的原因。此外,用單元測試和整合測試覆蓋 serverless 程式碼非常重要。

其次,就像微服務架構一樣,它具有大量的服務,但是關注的範圍很小,因此很難對 serverless 的元件進行監控,某些問題也很難檢測。總之,很難對不同的 serverless 元件之間的體系結構和依賴性有一個全面的認識。因此,雲提服務商和第三方公司都在提供監控和系統分析功能的一體式工具上投入了大量資金。

體驗一下 serverless 計算

現如今,根據業務需求快速進化的架構以往任何時候都更為重要。資料驅動的體驗是這個過程的一部分。此外,在釋出新功能之前,我們應該實現MVP(譯註:最小可行化產品)並在部分客戶群上測試它。如果實驗結果是肯定的,則值得在MVP上進行投資,以將其轉化為我們產品的功能。

是的,serverless 計算提供了這樣一種方法,可以在不考慮基礎設施的情況下快速進化我們的架構。Serverless 輕量級開銷提供了一種實現一次性 MVP 的方法,用於試驗新功能和新特性。此外,它們還可以很容易地啟動和關閉。

使用 .NET Core 來實現 AWS Lambda 函式

這一節將介紹使用 .NET Core 的一些 AWS Lambdas 的簡單實現。該例子涉及三個關鍵技術:

  • AWS 是承載我們 serverless 功能的雲服務商;
  • serverless 框架,它是將 Lambdas 放入 AWS 的非常有用的工具。作為一個通用的框架,它相容所有主要的雲服務商;
  • .NET Core 是微軟提供的開源的、跨平臺的框架;

我們將要討論的示例也放在了 GitHub 上,URL 如下: serverless/examples/aws-dotnet-rest-api-with-dynamodb。該示例是 serverless 框架提供的一些模板專案的一部分。

AWS Lambda 專案遵循以下功能架構:

總結一下,該功能實現了對資料的一些讀取/寫入操作。客戶端通過API閘道器發出HTTP請求,lambda 專案定義了三個函式:GetItem、InsertItem 和 UpdateItem。它們都對 DynamoDB 表進行操作。

專案結構

我們將要實現的解決方案具有以下專案結構:

  • src/DotNetServerless.Application 該專案包含了由 Serverless 執行的核心邏輯;
  • src/DotNetServerless.Lambda 該專案包含了 Serverless 函式的入口點以及所有與 AWS 緊密耦合的元件;
  • tests/DotNetServerless.Tests 該專案包含了 Serverless 功能的單元測試和整合測試;

領域專案

讓我們從 application 層開始分析。專案的核心實體是 Item 類,它表示 DynamoDB(譯註:AWS的一種資料庫) 表中儲存的實體:

using Amazon.DynamoDBv2.DataModel;

namespace DotNetServerless.Application.Entity
{
  public class Item
  {
    [DynamoDBHashKey]
    public string Id { get; set; }
    [DynamoDBRangeKey]
    public string Code { get; set; }
    [DynamoDBProperty]
    public string Description { get; set; }
    [DynamoDBProperty]
    public bool IsChecked { get; set; }
  }
}

實體的欄位使用了一些特性進行修飾,以便使用 DynamoDb 儲存模型對映它們。Item 實體被 IItemsRepository 介面引用,該介面定義用於儲存資料的操作:

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.DocumentModel;
using DotNetServerless.Application.Entities;
using DotNetServerless.Application.Infrastructure.Configs;

namespace DotNetServerless.Application.Infrastructure.Repositories
{
  public interface IItemRepository
  {
    Task<IEnumerable<T>> GetById<T>(string id, CancellationToken cancellationToken);

    Task Save(Item item, CancellationToken cancellationToken);
  }

  public class ItemDynamoRepository : IItemRepository
  {
    private readonly AmazonDynamoDBClient _client;
    private readonly DynamoDBOperationConfig _configuration;

    public ItemDynamoRepository(DynamoDbConfiguration configuration,
      IAwsClientFactory<AmazonDynamoDBClient> clientFactory)
    {
      _client = clientFactory.GetAwsClient();
      _configuration = new DynamoDBOperationConfig
      {
        OverrideTableName = configuration.TableName,
        SkipVersionCheck = true
      };
    }

    public async Task Save(Item item, CancellationToken cancellationToken)
    {
      using (var context = new DynamoDBContext(_client))
      {
        await context.SaveAsync(item, _configuration, cancellationToken);
      }
    }

    public async Task<IEnumerable<T>> GetById<T>(string id, CancellationToken cancellationToken)
    {
      var resultList = new List<T>();
      using (var context = new DynamoDBContext(_client))
      {
        var scanCondition = new ScanCondition(nameof(Item.Id), ScanOperator.Equal, id);
        var search = context.ScanAsync<T>(new[] {scanCondition}, _configuration);

        while (!search.IsDone)
        {
          var entities = await search.GetNextSetAsync(cancellationToken);
          resultList.AddRange(entities);
        }
      }

      return resultList;
    }
  }
}

IItemRepository 的實現定義了兩個基本操作:

  • Save,允許呼叫者插入和更新實體;
  • GetById,根據 ID 返回物件;

最後,DotNetServerless.Application 的頂層是 Handler 部分。並且
,整個 application 專案都基於中介模式,以保證 AWS 函式和核心邏輯之間的鬆散耦合。讓我們以建立專案處理程式的定義為例:

using System;
using System.Threading;
using System.Threading.Tasks;
using DotNetServerless.Application.Entities;
using DotNetServerless.Application.Infrastructure.Repositories;
using DotNetServerless.Application.Requests;
using MediatR;

namespace DotNetServerless.Application.Handlers
{
  public class CreateItemHandler : IRequestHandler<CreateItemRequest, Item>
  {
    private readonly IItemRepository _itemRepository;

    public CreateItemHandler(IItemRepository itemRepository)
    {
      _itemRepository = itemRepository;
    }

    public async Task<Item> Handle(CreateItemRequest request, CancellationToken cancellationToken)
    {
      var item = request.Map();
      item.Id = Guid.NewGuid().ToString();

      await _itemRepository.Save(item, cancellationToken);

      return item;
    }
  }
}

如您所見,程式碼非常簡單。CreateItemHandler 實現了 IRequestHandler,它使用內建的依賴注入來解析 IItemRepository 介面。處理程式的 Handler 方法僅將傳入的請求與Item實體對映,並呼叫IItemRepository介面提供的Save方法。

函式專案

函式專案包含 lambda 功能的入口點。它定義了三個函式類,它們表示 AWS 的 lambda:CreateItemFunction, GetItemFunction 和 UpdateItemFunction; 稍後我們將看到,每個函式都將使用 API 閘道器的特定路由進行對映。

讓我們以 CreateItem 函式為例,對函式定義進行一些深入探討:

using System;
using System.Threading.Tasks;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using DotNetServerless.Application.Requests;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace DotNetServerless.Lambda.Functions
{
  public class CreateItemFunction
  {
    private readonly IServiceProvider _serviceProvider;

    public CreateItemFunction() : this(Startup
      .BuildContainer()
      .BuildServiceProvider())
    {
    }

    public CreateItemFunction(IServiceProvider serviceProvider)
    {
      _serviceProvider = serviceProvider;
    }

    [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
    public async Task<APIGatewayProxyResponse> Run(APIGatewayProxyRequest request)
    {
      var requestModel = JsonConvert.DeserializeObject<CreateItemRequest>(request.Body);
      var mediator = _serviceProvider.GetService<IMediator>();
      
      var result = await mediator.Send(requestModel);

      return new APIGatewayProxyResponse { StatusCode =  201,  Body = JsonConvert.SerializeObject(result)};
    }
  }
}

上面提到的程式碼定義了函式的入口點。首先,它宣告一個建構函式,並使用Startup類公開的BuildContainer和BuildServiceProvider方法。稍後我們將看到,這些方法是為初始化依賴項注入容器而提供的。CreateItem 函式的 Run 方法使用 Lambda 序列器屬性進行修飾,這意味著它是函式的入口點。此外,執行函式使用 APIGatewayProxyRequest 請求和 APIGatewayProxyReposne 作為 lambda 計算的輸入和輸出。

依賴注入

該專案使用了 .NET Core 內建的依賴注入。Startup 類定義了 BuildContainer 靜態方法,該方法返回一個新的 ServiceCollection,其中包含實體之間的依賴關係對映:

using System.IO;
using DotNetServerless.Application.Infrastructure;
using DotNetServerless.Application.Infrastructure.Configs;
using DotNetServerless.Application.Infrastructure.Repositories;
using DotNetServerless.Lambda.Extensions;
using MediatR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace DotNetServerless.Lambda
{
  public class Startup
  {
    public static IServiceCollection BuildContainer()
    {
      var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddEnvironmentVariables()
        .Build();

      return ConfigureServices(configuration);
    }


    private static IServiceCollection ConfigureServices(IConfigurationRoot configurationRoot)
    {
      var services = new ServiceCollection();

      services
        .AddMediatR()
        .AddTransient(typeof(IAwsClientFactory<>), typeof(AwsClientFactory<>))
        .AddTransient<IItemRepository, ItemDynamoRepository>()
        .BindAndConfigure(configurationRoot.GetSection("DynamoDbConfiguration"), new DynamoDbConfiguration())
        .BindAndConfigure(configurationRoot.GetSection("AwsBasicConfiguration"), new AwsBasicConfiguration());

      return services;
    }
  }
}

Startup使用ConfigureServices初始化新的ServiceCollection並與其一起解決依賴關係。此外,它還使用 BindAndConfigure 方法建立一些配置物件。BuildContainer方法將由函式呼叫,以解決依賴項。

測試我們的程式碼

如前所述,測試一下我們的程式碼,對於持續整合和交付是非常重要的,尤其是在lambda專案中。在這種情況下,測試將覆蓋 IMediator 介面和處理程式之間的整合。此外,它們還覆蓋了依賴項注入部分。讓我們看看 CreateItemFunctionTests 的實現:

using System.Threading;
using System.Threading.Tasks;
using Amazon.Lambda.APIGatewayEvents;
using DotNetServerless.Application.Entities;
using DotNetServerless.Application.Infrastructure.Repositories;
using DotNetServerless.Application.Requests;
using DotNetServerless.Lambda;
using DotNetServerless.Lambda.Functions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Moq;
using Newtonsoft.Json;
using Xunit;

namespace DotNetServerless.Tests.Functions
{
  public class CreateItemFunctionTests
  {
    public CreateItemFunctionTests()
    {
      _mockRepository = new Mock<IItemRepository>();
      _mockRepository.Setup(_ => _.Save(It.IsAny<Item>(), It.IsAny<CancellationToken>())).Returns(Task.CompletedTask);

      var serviceCollection = Startup.BuildContainer();

      serviceCollection.Replace(new ServiceDescriptor(typeof(IItemRepository), _ => _mockRepository.Object,
        ServiceLifetime.Transient));

      _sut = new CreateItemFunction(serviceCollection.BuildServiceProvider());
    }

    private readonly CreateItemFunction _sut;
    private readonly Mock<IItemRepository> _mockRepository;

    [Fact]
    public async Task run_should_trigger_mediator_handler_and_repository()
    {
      await _sut.Run(new APIGatewayProxyRequest {Body = JsonConvert.SerializeObject(new CreateItemRequest())});
      _mockRepository.Verify(_ => _.Save(It.IsAny<Item>(), It.IsAny<CancellationToken>()), Times.Once);
    }
    
    [Theory]
    [InlineData(201)]
    public async Task run_should_return_201_created(int statusCode)
    {
      var result = await _sut.Run(new APIGatewayProxyRequest {Body = JsonConvert.SerializeObject(new CreateItemRequest())});
      Assert.Equal(result.StatusCode, statusCode);
    }
  }
}

如您所見,上述程式碼執行了我們的函式,並且對已注入的依賴項執行一些驗證,並驗證 IItemRepository 公開的 Save 方法是否被呼叫。因為一些原因,測試類並沒有覆蓋 DynamoDb 的特性。此外,當我們將複雜的實體和操作結合在一起時,可以使用 Docker 容器通過一些整合測試來覆蓋資料庫部分。對了,提到 .NET Core 和 AWS 的話題,.NET AWS 團隊有一個很好的工具來改進 lambda 的測試:LambdaTestTool

部署專案

讓我們來看看如何將專案匯入AWS。為此,我們將使用 serverless 框架。該框架的定義是:

serverless 框架是一個 CLI 工具,允許使用者構建和部署自動縮放、按執行付費、事件驅動的函式。

為了把 serverless 新增我們的專案,我們應該執行以下命令:

npm install serverless --save-dev

定義基礎架構

預設情況下,基礎架構的定義將放在 serverless.yml 檔案中。該檔案看起來像這樣:

service: ${file(env.configs.yml):feature}

frameworkVersion: ">=1.6.0 <2.1.0"

provider:
  name: aws
  stackName: ${file(env.configs.yml):feature}-${file(env.configs.yml):environment}
  runtime: dotnetcore2.1
  region: ${file(env.configs.yml):region}
  accountId: ${file(env.configs.yml):accountId}
  environment:
    DynamoDbConfiguration__TableName: ${file(env.configs.yml):dynamoTable}
    
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:*
      Resource: "arn:aws:dynamodb:${self:provider.region}:*:table/${self:provider.environment.DynamoDbConfiguration__TableName}"

package:
  artifact: bin/release/netcoreapp2.1/deploy-package.zip
  
functions:
  create:
    handler: DotNetServerless.Lambda::DotNetServerless.Lambda.Functions.CreateItemFunction::Run
    events:
      - http:
          path: items
          method: post
          cors: true

  get:
    handler: DotNetServerless.Lambda::DotNetServerless.Lambda.Functions.GetItemFunction::Run
    events:
      - http:
          path: items/{id}
          method: get
          cors: true

  update:
    handler: DotNetServerless.Lambda::DotNetServerless.Lambda.Functions.UpdateItemFunction::Run
    events:
      - http:
          path: items
          method: put
          cors: true

resources:
  Resources:
    ItemsDynamoDbTable:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          - AttributeName: Id
            AttributeType: S
          - AttributeName: Code
            AttributeType: S
        KeySchema:
          - AttributeName: Id
            KeyType: HASH
          - AttributeName: Code
            KeyType: RANGE
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DynamoDbConfiguration__TableName}

以上程式碼使用 AWS 的 cloud formation 對基礎架構進行一些操作。provider 節點定義了有關 lambda 的某些資訊,例如堆疊名稱、執行時以及有關AWS賬戶的一些資訊。此外,它還描述了 lambda 的角色和授權,例如,應該允許 lambda 對 DynamoDb 表執行操作。 functions 節點定義了不同的 lambda 函式,並將其與特定的 HTTP 路徑進行對映。最後,resources 節點用於設定 DynamoDB 表模式。

配置檔案

serverless.yml 定義通常與另一個 YAML 檔案結合使用,該檔案僅定義與環境相關的配置。例如,DynamoDbConfiguration__TableName 節點就是這種情況,該節點使用以下語法從另一個 YAML 檔案獲取資訊:${file(env.configs.yml):dynamoTable}。以下程式碼段顯示了 env.config.yml 檔案的一個示例:

feature: <feature_name>
version: 1.0.0.0
region: <aws_region>
environment: <environment>
accountId: <aws_account_id>
dynamoTable: <dynamo_table_name>

最後的想法

這篇文章涵蓋了一些關於 serverless 計算的理論主題,以及 .Net Core 實現 lambda 函式的例子。著重講解了如何使用 serverless 計算來快速推進我們的架構。此外,勇於嘗試是一個不斷髮展的產品很關鍵的一方面,它對於快速適應業務的變化是很重要的。

最後,您可以在以下儲存庫中找到一些 serverless 的 lambda 示例。
serverless/examples/aws-dotnet-rest-api-with-dynam