.NET Core 下使用 Apollo 配置中心


Apollo(阿波羅)是攜程框架部門研發的分布式配置中心,能夠集中化管理應用不同環境、不同集群的配置,配置修改后能夠實時推送到應用端,並且具備規范的權限、流程治理等特性,適用於微服務配置管理場景。服務端基於Spring Boot和Spring Cloud開發,打包后可以直接運行,不需要額外安裝Tomcat等應用容器。

Apollo開源地址:https://github.com/ctripcorp/apollo

更多產品介紹可以查看Apollo配置中心介紹,本篇主要介紹在 .NET 環境下如何使用 Apollo 配置中心。

Quick Start

為了方便,本次我選擇使用Docker部署,快速運用。

另外需要說明的是,不管是Docker方式部署Quick Start還是常規方式部署的,Quick Start只是用來快速入門、了解Apollo。如果部署Apollo在公司中使用,請參考分布式部署。

請確保開發環境有docker環境,然后下載docker-compose.yml和所需的sql文件,然后在根目錄執行docker-compose up,一次執行會觸發下載鏡像等操作,需要耐心等待一些時間。

version: '2'

services:
  apollo-quick-start:
    image: nobodyiam/apollo-quick-start
    container_name: apollo-quick-start
    depends_on:
      - apollo-db
    ports:
      - "8080:8080"
      - "8070:8070"
    links:
      - apollo-db

  apollo-db:
    image: mysql:5.7
    container_name: apollo-db
    environment:
      TZ: Asia/Shanghai
      MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
    depends_on:
      - apollo-dbdata
    ports:
      - "13306:3306"
    volumes:
      - ./sql:/docker-entrypoint-initdb.d
    volumes_from:
      - apollo-dbdata

  apollo-dbdata:
    image: alpine:latest
    container_name: apollo-dbdata
    volumes:
      - /var/lib/mysql

搜索所有apollo-quick-start開頭的日志,看到以下日志說明啟動成功:

apollo-quick-start    | Waiting for config service startup.....
apollo-quick-start    | Config service started. You may visit http://localhost:8080 for service status now!
apollo-quick-start    | Waiting for admin service startup.
apollo-quick-start    | Admin service started
apollo-quick-start    | ==== starting portal ====
apollo-quick-start    | Portal logging file is ./portal/apollo-portal.log
apollo-quick-start    | Started [239]
apollo-quick-start    | Waiting for portal startup....
apollo-quick-start    | Portal started. You can visit http://localhost:8070 now!

數據庫的端口映射為13306,所以如果希望在宿主機上訪問數據庫,可以通過localhost:13306,用戶名是root,密碼留空。如要查看更多服務的日志,可以通過docker exec -it apollo-quick-start bash登錄, 然后到/apollo-quick-start/service和/apollo-quick-start/portal下查看日志信息。

訪問http://localhost:8070,可以看到ApolloUI界面,默認賬號密碼為:apollo/admin

.NET Core 接入

新建一個 ASP.NET Core API項目,ApolloDemo,添加組件Com.Ctrip.Framework.Apollo.Configuration

Install-Package Com.Ctrip.Framework.Apollo.Configuration

Apollo配置中心的 .NET 集成包開源地址:https://github.com/ctripcorp/apollo.net/tree/dotnet-core

接入也比較簡單,在appsettings.json中配置Apollo服務地址。

{
  "Apollo": {
    "AppId": "ApolloDemo",
    "Env": "DEV",
    "MetaServer": "http://localhost:8080",
    "ConfigServer": [ "http://localhost:8080" ]
  }
}

關於配置可以查看文檔:https://github.com/ctripcorp/apollo.net/tree/dotnet-core/Apollo.Configuration

為什么地址端口是8080而不是8070?

因為在docker-compose.yml中我們暴露兩個端口:8080個8070,8070是我們的Apollo配置中心管理界面,而8080端口是Spring Eureka服務注冊中心。所以配置的應該是服務端的地址。

緊接着在Program.cs應用配置,代碼如下:

using Com.Ctrip.Framework.Apollo;
using Com.Ctrip.Framework.Apollo.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace ApolloDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, builder) =>
                {
                    LogManager.UseConsoleLogging(LogLevel.Trace);

                    builder.AddApollo(builder.Build().GetSection("Apollo")).AddDefault();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

然后我們在Apollo管理界面新建一個與配置在appsettings.json中AppId同名的項目ApolloDemo

Apollo有一個核心的概念:Namespace

  • Namespace是配置項的集合,類似於一個配置文件的概念。
  • Namespace類型有三種:私有類型、公共類型、關聯類型(繼承類型)。
  • Namespace的獲取權限分為兩種:private (私有的)、public (公共的),這里的獲取權限是相對於Apollo客戶端來說的。

配置文件有多種格式,例如:properties、xml、yml、yaml、json等。同樣Namespace也具有這些格式。在Portal UI中可以看到“application”的Namespace上有一個“properties”標簽,表明“application”是properties格式的。

非properties格式的namespace,在客戶端使用時需要調用ConfigService.getConfigFile(String namespace, ConfigFileFormat configFileFormat)來獲取,如果使用Http接口直接調用時,對應的namespace參數需要傳入namespace的名字加上后綴名,如datasources.json。
apollo-client 1.3.0版本開始對yaml/yml做了更好的支持,使用起來和properties格式一致:Config config = ConfigService.getConfig("application.yml");,Spring的注入方式也和properties一致。

關於Namespace`的文檔:https://github.com/ctripcorp/apollo/wiki/Apollo核心概念之“Namespace”

接下來去新增幾個配置屬性,然后發布。


現在去寫一個接口,來實時讀取Apollo中的配置。

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace ApolloDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        [Route("Apollo")]
        public IActionResult ApolloTest([FromServices] IConfiguration configuration, string key)
        {
            return Content(configuration.GetValue<string>(key));
        }
    }
}

使用起來也非常簡單,這里根據傳入的key值不同,獲取到我們配置在Apollo中的value,並且是具有熱更新,實時動態改變的。

然后修改name和age的值,在調用接口看看。注意在Apollo中修改后,需要發布才會生效。


簡單介紹了 .NET Core 下使用Apollo配置中心,Apollo的功能遠不止於此,根據需要可以去Github查看官網Wiki介紹,有詳細的使用說明文檔。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM