天天看點

給你的 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 是支援百分比的随機開關,通過使用這種方式,可以讓一個功能在每次請求中以一個百分比機率的形式來開啟/關閉。
  • 注入功能開關

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>
           

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

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

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"
          }
        }
      ]
    }
  }
           
這裡需要注意的是,配置裡面的

Start

End

DateTimeOffset

類型,并且需要配置為 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>
           
給你的 ASP.NET Core 程式插上 Feature Flag 的翅膀

自定義功能開關

最後要介紹的是如果建立和使用自定義的功能開關,筆者這裡做一個這樣的示例,當網站被 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 通路站點時就會看到如下圖所示的效果:

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

總結

借助于 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