1. 程式人生 > >給你的 ASP.NET Core 程式插上 Feature Flag 的翅膀

給你的 ASP.NET Core 程式插上 Feature Flag 的翅膀

前言

我們知道,目前大多數應用程式在正式釋出到生產環境之前都會經歷多個不同的測試環境,通過讓應用程式在多個不同的環境中執行來及時發現並解決問題,避免在線上發生不必要的損失。這是對於整個軟體的釋出流程來講。但是如果想讓我們的應用程式在線上環境中通過滿足一些動態條件(比如電商平臺在某一時間段的促銷活動)從而能開啟一些臨時功能的話又該怎麼辦呢?如果你試圖通過重新打包釋出的方式來解決這個問題,可能有些過於大動干戈了。本文,筆者將介紹通過 Feature Flag 的方式來解決這個問題。

正文

Feature Flag 中文可譯為 功能開關。通過使用這種方式,可以對我們的功能進行條件化配置,當程式在線上環境執行時,如果當前環境符合我們某一特性功能開啟/關閉的條件時,應用程式會自動開啟/關閉該功能。整個過程不需要人工參與,全部都是由系統本身來完成相應功能的開啟和關閉。

那在 .NET Core 中,我們該如何實現該功能呢?

微軟為我們很貼心地提供了兩個開發包:Microsoft.FeatureManagement 和 Microsoft.FeatureManagement.AspNetCore,該實現是基於 .NET Core 的配置系統 ,所以任何 .NET Core 程式都可以輕易整合該功能。

目前還處於預覽版階段,需要在 NuGet 上勾選 use prerelease

因此,我們只需將對應包安裝到我們的應用程式中即可。

接下來,我們就一起看一下如何在 ASP.NET Core 中整合該功能。

使用入門

建立一個 ASP.NET Core Web Application 後,安裝如下包:

Install-Package Microsoft.FeatureManagement.AspNetCore -Version 2.0.0-preview-010610001-1263

接著在 Startup 中的 ConfigureServices 進行相應配置,示例如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddFeatureManagement();
    services.AddControllersWithViews();
}

至此,我們的程式已經支援 Feature Flag 功能了,使用方式就簡單了,這裡展示一個相對簡單的方式。

首先,在 appsettings.json 進行配置,如下所示:

  "FeatureManagement": {
    "NewFeatureFlag": true,
  }

然後,在 Index.cshtml 通過使用 feature 標籤來進行相應配置,示例如下所示:

@using Microsoft.FeatureManagement
@inject IFeatureManager FeatureManager
@addTagHelper *,Microsoft.FeatureManagement.AspNetCore
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>

    <feature name="NewFeatureFlag" requirement="All">
        <a asp-action="NewFeature">Go to the new feature.</a>
    </feature>
</div>

此時,我們執行起程式後就可以看到 feature 標籤內的內容就可以渲染出來,如果我們在配置中將 NewFeatureFlag 值設定為 False 後,feature 標籤內的內容就會消失,你可以通過檢視網頁原始碼的方式來檢視具體細節。

接下來筆者介紹一下微軟為我們內建的兩個功能開關:

  • PercentageFilter
  • TimeWindowFilter

PercentageFilter

PercentageFilter 是支援百分比的隨機開關,通過使用這種方式,可以讓一個功能在每次請求中以一個百分比概率的形式來開啟/關閉。

  • 注入功能開關

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddFeatureManagement()
        .AddFeatureFilter<PercentageFilter>();
    services.AddControllersWithViews();
}
  • 配置功能開關

appsettings.json

  "FeatureManagement": {
    "RandomFlag": {
      "EnabledFor": [
        {
          "Name": "Percentage",
          "Parameters": {
            "Value": 50
          }
        }
      ]
    }
  }

這裡配置的是在每次請求時以 50% 的概率來開啟該功能,其對應的配置類為:PercentageFilterSettings

  • 使用功能開關

Index.cshtml

@using Microsoft.FeatureManagement
@inject IFeatureManager FeatureManager
@addTagHelper *,Microsoft.FeatureManagement.AspNetCore
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>

    <feature name="RandomFlag">
        <h2>I am a Random Flag!</h2>
    </feature>
    
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

這時,當我們執行起程式後就會看到如下圖所示的效果:

TimeWindowFilter

TimeWindowFilter 是時間段的隨機開關,通過使用這種方式,可以讓一個功能在指定的時間段內來開啟/關閉。

  • 注入功能開關

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddFeatureManagement()
        .AddFeatureFilter<TimeWindowFilter>();
    services.AddControllersWithViews();
}
  • 配置功能開關

appsettings.json

  "FeatureManagement": {
    "RandomFlag": {
      "EnabledFor": [
        {
          "Name": "Percentage",
          "Parameters": {
            "Start": "2019/12/27 5:04:00 +00:00",
            "End": "2019/12/27 5:04:05 +00:00"
          }
        }
      ]
    }
  }

這裡需要注意的是,配置裡面的 StartEndDateTimeOffset 型別,並且需要配置為 UTC 的時間,所以在實際使用過程中需要考慮時區問題(你可以通過呼叫 DateTimeOffset.UtcNow 的方式來獲取相應時間的格式)。其對應的配置類為:TimeWindowFilterSettings

  • 使用功能開關

Index.cshtml

@using Microsoft.FeatureManagement
@inject IFeatureManager FeatureManager
@addTagHelper *,Microsoft.FeatureManagement.AspNetCore
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>

    <feature name="TimedFlag">
        <h2>I am a Timed Flag!</h2>
    </feature>
    <p>@DateTimeOffset.UtcNow.ToString()</p>
    
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

這時,當我們執行起程式後就會看到如下圖所示的效果:

自定義功能開關

最後要介紹的是如果建立和使用自定義的功能開關,筆者這裡做一個這樣的示例,當網站被 Microsoft Edge 瀏覽器訪問時,顯示功能,其餘瀏覽器則隱藏功能。

這裡,筆者建立一個配置的對映類 BrowserFilterSettings 和執行過濾的操作類 BrowserFeatureFilter,示例程式碼如下所示:

public class BrowserFilterSettings
{
    public string[] AllowedBrowsers { get; set; }
}

[FilterAlias("BrowserFilter")]
public class BrowserFeatureFilter : IFeatureFilter
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public BrowserFeatureFilter(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
    public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context)
    {
        var userAgent = _httpContextAccessor.HttpContext.Request.Headers["User-Agent"].ToString();
        var settings = context.Parameters.Get<BrowserFilterSettings>();
        return Task.FromResult(settings.AllowedBrowsers.Any(userAgent.Contains));
    }
}

接著,進行功能開關的注入,示例程式碼如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddFeatureManagement()
        .AddFeatureFilter<BrowserFeatureFilter>();
    services.AddControllersWithViews();
}

然後,進行功能開關的配置,示例配置如下所示:

  "FeatureManagement": {
    "BrowserFlag": {
      "EnabledFor": [
        {
          "Name": "BrowserFilter",
          "Parameters": {
            "AllowedBrowsers": [
              "Edge"
            ]
          }
        }
      ]
    }
  }

接著,使用方式如下所示:

@using Microsoft.FeatureManagement
@inject IFeatureManager FeatureManager
@addTagHelper *,Microsoft.FeatureManagement.AspNetCore
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>

    <feature name="BrowserFlag">
        <h2>I am a Browser Flag only on Edge!</h2>
    </feature>
    
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

這時,當我們分別用 Microsoft Edge 和 Google Chrome 訪問站點時就會看到如下圖所示的效果:

總結

藉助於 Microsoft.FeatureManagement.AspNetCore 擴充套件包,我們可以很容易實現 Feature Flag 效果。又由於這種實現是基於 IConfiguration 的,所以很具有通用性。這裡列出官方給出的優點:

  • A common convention for feature management
  • Low barrier-to-entry
    • Built on IConfiguration
    • Supports JSON file feature flag setup
  • Feature Flag lifetime management
    • Configuration values can change in real-time, feature flags can be consistent across the entire request
  • Simple to Complex Scenarios Covered
    • Toggle on/off features through declarative configuration file
    • Dynamically evaluate state of feature based on call to server
      API extensions for ASP.NET Core and MVC framework
    • Routing
    • Filters
    • Action Attributes

非常感謝你能閱讀這篇文章,希望它能對你有所幫助。

相關參考

  • FeatureManagement-Dotnet
  • Microsoft.FeatureManagement
  • Tutorial: Use feature flags in an ASP.NET Core app
  • Using custom Feature Flag filters in .NET Core