注意:因为项目是聚合项目,parent里面导入了勒eureka的client依赖,因为这个问题卡了一下午。大家可以注意一下。
com.ctrip.framework.apollo
apollo-client
1.1.1
server:
port: 1111
app:
id : apollo-test
apollo:
meta: http://127.0.0.1:8080
eureka:
client:
register-with-eureka: false
fetch-registry: false
注意:(1)这里的8080端口,不是,euruka server的端口,而是apollo涉及的三大端口之一(8080,8070,8090).
(2)id对应是apollo项目的id,不了解的可以查看之前的博客https://blog.csdn.net/qq_16855077/article/details/103197221
(3) 因为聚合父pom.xml中引入了euraka client,而eurake和apollo这里会有一个小问题,需要把client对应的值都改为false。
具体报错:https://blog.csdn.net/qq_16855077/article/details/103260026
package com.fqyd.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Description:
* Author: wude
* Date: 2019/11/26 11:34
* Modified By:
*/
@RestController
public class TestController {
@Value("${jdbc.username}")
private String jdbcUsername;
@GetMapping("/hello")
public String helloApollo(){
return "hello "+jdbcUsername;
}
}
package com.fqyd;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableApolloConfig //启用apollo配置
@SpringBootApplication
public class ApolloTestApplication {
public static void main(String[] args) {
SpringApplication.run(ApolloTestApplication.class, args);
}
}
注意:记得启用apollo的配置
http://localhost:1111/hello
到这里,简单的读取配置就实现了。
server:
port: 1111
app:
id : apollo-test
apollo:
meta: http://127.0.0.1:8080
bootstrap:
###启用apollo配置开关
enabled: true
# apollo 使用配置的命名空间,多个以逗号分隔
namespaces: application,springMQ,TEST3.commom
eureka:
client:
register-with-eureka: false
fetch-registry: false
package com.fqyd.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Description:
* Author: wude
* Date: 2019/11/26 11:34
* Modified By:
*/
@RestController
public class TestController {
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${FILE_NAME}")
private String helloUsername;
@Value("${server.zookeeper}")
private String zk;
@GetMapping("/hello")
public String helloApollo(){
return "hello "+jdbcUsername;
}
/**
* 测试namespacen调用
* @return
*/
@GetMapping("/testNamespace")
public String testNamespace(){
return "测试testNamespace读取:"+helloUsername;
}
/**
* 测试调用公有配置
* @return
*/
@GetMapping("/testPublic")
public String testPublic(){
return "testPublic读取:"+zk;
}
}
通过测试,发现调用其他的namespaces也是可以成功的,调用公有的namespace也可以成功,但是,如果配置的属性名一样,apollo是以application空间下的为准。
输出是少了一个123,说明是以application为准,应避免属性名重复。
如果你热衷技术,喜欢交流,欢迎加入我们!