Loading

Apollo客户端集成

(1) 引入依赖

Apollo的客户端jar包已经上传到中央仓库,应用在实际使用时只需要按照如下方式引入即可。

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

方式一:

配置文件引入:

server:
  port: 9001 #端口
spring:
  application:
    name: service-product #服务名称
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    database: MySQL
    show-sql: true
    open-in-view: true
name: yyj
apollo:
  bootstrap: #开启apollo
    enabled: true
  meta: http://192.168.74.101:8080 # 服务端的Eureka地址
app:
  id: product-service  #指定apollo配置中心中的appId

在controller中测试:

@RestController
@RequestMapping("/product")
public class ProductController {

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

    @RequestMapping(value = "/test")
    public String test() {
        return name;
    }
}

通过在apllo中修改配置文件key是name,value是自定义内容,之后发布后再次访问,配置文件内容即实时的发生改变。

方式二:

(2)Spring Boot集成

Spring Boot支持通过application.properties/bootstrap.properties来配置,该方式能使配置在更早的阶段注入,比如使用 @ConditionalOnProperty 的场景或者是有一些spring-boot-starter在启动阶段就需要读取配置做一些事情(如dubbo-spring-boot-project),所以对于Spring Boot环境建议通过以下方式来接入Apollo(需要0.10.0及以上版本)。

使用方式很简单,只需要在application.properties/bootstrap.properties中按照如下样例配置即可。

1. 注入默认 application namespace的配置示例

# will inject 'application' namespace in bootstrap phase
apollo.bootstrap.enabled = true

2.注入非默认 application namespace或多个namespace的配置示例

apollo.bootstrap.enabled = true
apollo.bootstrap.namespaces = application,FX.apollo,application.yml

3.将Apollo配置加载提到初始化日志系统之前(1.2.0+)

从1.2.0版本开始,如果希望把日志相关的配置(如 logging.level.root=info 或 logback-spring.xml 中的参数)也放在Apollo管理,那么可以额外配置apollo.bootstrap.eagerLoad.enabled=true 来使Apollo的加载顺序放到日志系统加载之前,不过这会导致Apollo的启动过程无法通过日志的方式输出(因为执行Apollo加载的时候,日志系统压根没有准备好呢!所以在Apollo代码中使用Slf4j的日志输出便没有任何内容),更多信息可以参考PR 1614。参考配置示例如下:

# will inject 'application' namespace in bootstrap phase
apollo.bootstrap.enabled = true
# put apollo initialization before logging system initialization
apollo.bootstrap.eagerLoad.enabled=true

 

posted @ 2021-07-29 16:23  1640808365  阅读(101)  评论(0编辑  收藏  举报