SpringBoot整合 Apollo 入門
阿新 • • 發佈:2021-10-31
基礎概念
- 官方文件(官網介紹較為詳細,不再贅述)
https://www.apolloconfig.com/#/zh/design/apollo-introduction
SpringBoot整合
一.官網給予了基礎的Quick Start,可參考學習入門 ,(win平臺啟動可以使用git客戶端執行sh指令碼)
$ sh ./demo.sh start
Windows new JAVA_HOME is: /d/DevProgram/Java/jdk
==== starting service ====
Service logging file is ./service/apollo-service.log
Started [1121]
Waiting for config service startup...
看到Started [1121]即表示成功!
二.這裡給出在springboot工程中如何使用的簡單demo
1.首先參考Quick Start文件,搭建基礎環境,包括 Apollo config應用和資料庫等
2.新建springboot 工程,匯入web依賴和Apollo client依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <groupId>com.ggq</groupId> <artifactId>springboot-apollo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- web功能起步依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- apollo 客戶端依賴--> <dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>1.3.0</version> </dependency> </dependencies> </project>
2.主啟動類
package com.ggq; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; @SpringBootApplication @EnableApolloConfig //此處開啟apollo配置 public class ApolloClientStart { public static void main(String[] args) { SpringApplication.run(ApolloClientStart.class,args); } }
3.構建基礎配置檔案,指定apollo配置中心地址和應用本身id等
server:
port: 8081
app:
id: springboot-apollo
apollo:
meta: http://127.0.0.1:8080
bootstrap:
enabled: true
eagerLoad:
enabled: true
4.測試類
package com.ggq.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Value( "${name}" )
private String name;
@RequestMapping("/name")
public String ReadName() {
return "我的名字是:"+this.name;
}
}
訪問http://localhost:8081/name,可以得到我的名字是:張三 ,重新在apollo中配置name值無需重啟,再次請求
http://localhost:8081/name,可得到我的名字是:李四