本文將介紹如何讓現(xiàn)有的Spring Boot項目接入Apollo,還未搭建Apollo服務(wù)端的請移步到我前面的文章進行閱讀。
下面以Cas單點登錄項目為例,進行簡單的接入操作,更多詳細的方法請參考:
[github官方文檔] https://github.com/ctripcorp/apollo/wiki/Java客戶端使用指南
一、創(chuàng)建配置信息
接入之前,需要先在Apollo服務(wù)器創(chuàng)建需要的配置項。
默認訪問:localhost:8070創(chuàng)建項目

添加并發(fā)布配置項

二、客戶端接入
1.添加依賴
<!-- apollo客戶端 -->
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.4.0</version>
</dependency>
2.啟動aopollo配置中心
方式一:
修改application.properties或bootstrap.properties配置
apollo.bootstrap.enabled=true
方式二:
在啟動類添加@EnableApolloConfig注解。
@EnableTransactionManagement
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
@EnableEurekaClient
@EnableApolloConfig
public class MainWebApplication extends SpringBootServletInitializer {
@Profile("war")
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MainWebApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MainWebApplication.class, args);
}
}
目前在我們公司的項目中,cas使用第一種方式,其他項目使用第二種方式。因為cas單點登錄的啟動類不是我們自定義的,直接在配置文件中配置比較方便。
其他方式這里不進行介紹了,想具體了解的可以到官網(wǎng)。
2.配置AppId和meta-server
方式一:
在application.properties或者bootstrap.properties中按照如下樣例進行配置
#這兩個屬性配置不支持多個war包在同一個tomcat中啟動,需要在classpath:META-INF/app.properties文件中配置
app.id=apollo-cas
#apollo.meta只是一個邏輯角色,在部署時和Config Service是在一個JVM進程中的,所以IP、端口和Config Service一致
apollo.meta=http://localhost:8080
這種配置方式不適用于多個war包部署在同一個tomcat的使用場景,考慮到我們公司雖然是做往微服務(wù)方向發(fā)展,但是可能也會以war包的形式部署到同一個tomcat,所以我沒采用這種方式,而是采用了第二種方式。
方式二:
在resources/META-INF/目錄下創(chuàng)建app.properties文件,把app.id和apollo.meta的配置移到該配置文件.
下圖中,我采用了占位符形式是為了便于實施人員在Maven編譯部署時可以以設(shè)置變量的方式進行賦值,避免更改配置文件(這里可以不用Maven設(shè)置變量的方式,直接寫configserver的地址也可以。)。而開發(fā)人員在本地進行開發(fā)時,可以在通過server.properties配置文件來進行配置apollo.meta,因為通過server.properties配置的方式優(yōu)先級比在app.properties配置的方式高。

使用Maven設(shè)置變量的方式需要在pom.xml文件添加resources標簽
<resources>
<resource>
<directory>src/main/resources/META-INF/</directory>
<targetPath>/META-INF</targetPath>
<includes>
<include>app.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
通過server.properties配置文件
可以在
server.properties配置文件中指定apollo.meta=http://config-service-url對于Mac/Linux,文件位置為
/opt/settings/server.properties對于Windows,文件位置為
C:\opt\settings\server.properties
env=DEV
apollo.meta=http://192.168.10.126:8080
3.測試
@RestController
@RequestMapping("test")
public class TestController {
@Value("${testname:}")
private String testName;
@GetMapping("hello")
public String hello() {
return "hello: " + testName;
}
}
啟動Cas成功,登錄后,訪問上面的測試接口:

apollo配置起效。