maven 依赖
apollo 服务未搭建点击https://blog.csdn.net/fengchen0123456789/article/details/86605056
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-core</artifactId>
<version>1.0.0</version>
</dependency>
如依赖下不下来,则下载源码 https://github.com/ctripcorp/apollo,打开里面的scripts文件夹,运行 build.sh ,win系统 运行 build.bat 即可,我的不知道怎么回事,启动报找不到 Gson依赖,在加入
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
配置
首先修改环境
linux : /opt/settings/server.properties
Windows : C:\opt\settings\server.properties
填入 env=DEV
没有相应目录,则新建
springboot配置
application.properties
# 项目端口号
server.port = 8185
# apollo web 配置页面的应用id
app.id = apollo-demo1
# apollo meta 地址
apollo.meta = http://127.0.0.1:8080
本地缓存
Apollo客户端会把从服务端获取到的配置在本地文件系统缓存一份,用于在遇到服务不可用,或网络不通的时候,依然能从本地恢复配置,不影响应用正常运行
缓存路径格式
Mac/Linux: /opt/data/{appId}/config-cache
Windows: C:\opt\data{appId}\config-cache
注意,如是linux ,请确保在opt有写入权限
执行
sudo chmod -R 777 opt
对opt下所有文件夹有写入,这里只是举个例子
也可以自定义目录
方法1 application.properties 加入
apollo.cacheDir = /opt/data/cache
方法2 可以在server.properties配置文件中指定
apollo.cacheDir = /opt/data/cacheir
启动测试
访问 http://127.0.0. 1: 8070 ,创建项目,应用id为 apollo-demo1,新建两个配置参数 hello,cache
springboot 启动类
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableApolloConfig
@SpringBootApplication
public class ApolloApplication {
public static void main(String[] args) {
SpringApplication.run(ApolloApplication.class, args);
}
}
Controller 类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
// 如 参数 hello 未获取到值,则使用: 后面的值
@Value("${hello:apollo.hello}")
private String hello;
@Value("${cache:apollo.cache}")
private String cache;
@GetMapping("/hello")
public String hello() {
return hello + " ;cache:" + cache;
}
}
启动好之后 ,访问自己项目的路径,在修改apollo里的参数,不重启本地的springboot项目,在获取2个参数值,跟着变,整合成功