1. 程式人生 > 其它 >springboot 整合 Apollo 動態獲取配置檔案的方法

springboot 整合 Apollo 動態獲取配置檔案的方法

如果你要自己搭建Apollo環境的話參考: 

https://blog.csdn.net/qq_38983728/article/details/90108387

https://www.bilibili.com/video/BV1qt4117789

我是懶得搞,公司有現成的,下面說說咋整合使用

 

maven依賴

<dependency>
            <groupId>com.ctrip.framework.apollo</groupId>
            <artifactId>apollo-client</artifactId>
            <version>1.1.2</version>
</dependency>

 

application.yml

app:
  id: edu_xxx_service
apollo:
  bootstrap:
    enabled: true
    namespaces: application,application-volatile         //獲取對應名稱空間的配置
  meta: 'http://0000000'      //Apollo地址服務地址
  
//app.id:在配置中心配置的應用身份資訊。
//apollo.bootstrap.enabled:在應用啟動階段是否向Spring容器注入被託管的properties檔案配置資訊。
//apollo.bootstrap.eagerLoad.enabled:將Apollo配置載入提到初始化日誌系統之前。
//apollo.bootstrap.namespaces:配置的名稱空間,多個逗號分隔,一個namespace相當於一個配置檔案。

 

control層

package com.nnn.apollo.control;

import com.nnn.apollo.ent.ValueStyleProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/value-style")
public class ValuePropertyController {

    @Autowired
    private ValueStyleProperty keyProperty;

    @Value("${server.port:123}")            ---取的是配置檔案 ,如果沒有填入123 的寫法
    private String port;

    @Value("${apollo.bootstrap.namespaces}")  ---取的是配置檔案              
    private String namespaces;

    @GetMapping("/get")
    public Map<String, Object> getProperty() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("port", port);
        map.put("namespaces", namespaces);                  ----獲取啟動時獲取哪些應用的配置
        map.put("topic.name", keyProperty.getDemoKey1());   ----獲取配置檔案name對應的值
        return map;
    }

}

 

實體類

ValueStyleProperty

package com.nnn.apollo.ent;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Data
//其實就是搞個實體類 取配置檔案裡面的值 賦值過來而已
public class ValueStyleProperty {

    @Value("${topic.name}") 
    private String demoKey1;
}

 

啟動類

package com;

import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
//在微服務應用啟動中使用apollo配置中心獲取配置資訊
@EnableApolloConfig
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(SecurityApplication.class, args);
    }

}

 

其實阿,apollo用這個,當在apollo修改配置後,客戶端已編譯在跑的專案的配置檔案 就會同步修改,那麼專案就不用重啟啦。

檢視從apollo拉取回來的配置檔案 可以找以下位置檢視

 

 

然後拉取來的配置檔案資訊會覆蓋本地的配置檔案資訊,當然apollo裡面沒有的就用原來本地的