spring cloud+.net core搭建微服務架構:配置中心(四)

前言

咱們項目中有不少須要配置的地方,最多見的就是各類服務URL地址,這些地址針對不一樣的運行環境還不同,無論和打包仍是部署都麻煩,須要很是的當心。通常配置都是存儲到配置文件裏面,無論多小的配置變更,都須要對應用程序進行重啓,對於分佈式系統來講,這是很是不可取的。因此配置中心就在這種場景孕育出來,可以適配不一樣的環境,正在運行的程序不用重啓直接生效。html

介紹

如今開始介紹咱們今天的主角spring cloud config,我以爲它最大的優勢就是能夠和git作集成,使用起來很是方便。spring cloud config包含服務端和客戶端,服務端提供配置的讀取和配置倉庫,客戶端來獲取配置。java

也可使用svn或者文件來存儲配置文件,咱們這裏只講Git的方式git

業務場景

咱們模擬一個業務場景,有一個遠程配置文件咱們經過應用程序獲取它。github

代碼實現

咱們須要建立2個應用程序:配置服務服務端(Java),配置服務客戶端(.Net Core)和一個Github倉庫。
使用IntelliJ IDEA建立一個spring boot項目,建立配置中心服務端,端口設置爲5100web

pom.xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
ConfigServerApplication.java
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}
application.properties
server.port=5100
spring.application.name=config-server
#git倉庫地址
spring.cloud.config.server.git.uri=https://github.com/longxianghui/configs.git
#git用戶名和密碼
#spring.cloud.config.server.git.username=xxx
#spring.cloud.config.server.git.password=xxx
#git目錄下的文件夾,多個用逗號分割
#spring.cloud.config.server.git.search-paths=xxx,xxx,xxx

使用Github建立一個倉庫,並提交3個文件,文件內容以下(注意yml格式)spring

demo-dev.yml
name: mickey
age: 3
env: test
demo-test.yml
name: fiona
age: 28
env: test
demo-prod.yml
name: leo
age: 30
env: prod

配置文件命名規則{application}-{profile}.yml
支持yml和properties格式json

運行配置中心服務端
在瀏覽器輸入http://localhost:5001/demo/dev
image
再訪問http://localhost:5001/demo/test
image
再訪問http://localhost:5001/demo/prod
image
經過上面3個URL咱們發現配置中心經過REST的方式將配置信息返回。
配置服務REST規則以下:api

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties瀏覽器

下面咱們再看看.NET程序如何讀取配置信息呢?
建立一個 .net core web api程序,端口5101架構

nuget引用
<PackageReference Include="Steeltoe.Extensions.Configuration.ConfigServer" Version="1.1.0" />
appsettings.json
{
  "spring": {
    "application": {
      "name": "demo"//與配置文件的名稱對應
    },
    "cloud": {
      "config": {
        "uri": "http://localhost:5100",
        "env": "dev" //與環境名稱對應
      }
    }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
Startup.cs
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables()
        .AddConfigServer(env);
    Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddConfigServer(Configuration);
    // Add framework services.
    services.AddMvc();
    services.Configure<Demo>(Configuration);
}
Demo.cs
public class Demo
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Env { get; set; }
}
ValuesController.cs
[Route("/")]
public class ValuesController : Controller
{
    private readonly IConfigurationRoot _config;
    private readonly IOptionsSnapshot<Demo> _configDemo;

    public ValuesController(IConfigurationRoot config, IOptionsSnapshot<Demo> configDemo)
    {
        _config = config;
        _configDemo = configDemo;
    }
    [HttpGet]
    public Demo Get()
    {
        //兩種方式獲取配置文件的數據
        //var demo = new Demo
        //{
        //    Name = _config["name"],
        //    Age = int.Parse(_config["age"]),
        //    Env = _config["env"]
        //};
        var demo = _configDemo.Value;
        return demo;
    }
}

運行程序 瀏覽器訪問http://localhost:5101/,
image
更改配置文件appsettings.json,"env": "test",從新啓動程序,刷新頁面
image
再更改配置文件appsettings.json,"env": "prod",程序啓動程序,刷新頁面
image
這樣經過修改本地的配置文件,就能獲取遠程上的各類配置了。
咱們再試試修改遠程的配置文件,修改demo-prod.yml的配置name: leo1,提交到github。
再訪問http://localhost:5011/,發現配置並無變化,這是由於配置服務並不知道git有更新,咱們重啓配置服務,再次訪問,問題依舊,那麼再重啓客戶端,發現咱們獲得了剛纔更新的配置name= leo1,配置生效了。
image

後記

經過上面的例子,咱們可以經過應用程序獲取到配置信息,可是這有明顯的問題,總不能一有配置更新就去重啓配置服務和客戶端吧?如何作到自動通知到客戶端呢?留下這些問題,敬請期待下一章。

示例代碼

全部代碼均上傳github。代碼按照章節的順序上傳,例如第一章demo1,第二章demo2以此類推。
求推薦,大家的支持是我寫做最大的動力,個人QQ羣:328438252,交流微服務。

傳送門

參考資料

java部分

.net部分

相關文章
相關標籤/搜索