继前一篇文章《揭秘!微服务架构下,Apollo 配置中心凭啥扮演关键角色?》之后,今天我们就来探讨下SpringBoot项目中如何启用Apollo的客户端,以及启用时它做了哪些工作。
SpringBoot项目如何启用Apollo客户端?
首先在pom.xml引入apollo客户端的依赖。
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>${version}</version>
<!--最新的版本是2.3.0-->
</dependency>
接下来,在.yml中加入apollo的相关配置。
app:
id: 你的服务名
apollo:
bootstrap:
# 启用 Apollo 的自动配置功能
enabled: true
# 指定应用需要从 Apollo 获取的配置命名空间列表
namespaces: application,datasource
# Apollo 配置中心地址,即服务端地址
meta: http://localhost:8080
最后在启动类中加上@EnableApolloConfig注解即可启用Apollo客户端。
@SpringBootApplication
@EnableApolloConfig
public class Main {
public static void main(String[] avg) {
SpringApplication.run(Main.class, args);
}
}
Apollo客户端在启动时都做了哪些工作?
了解@EnableApolloConfig 注解是解读Apollo客户端启动机制的关键。此注解通过@Import注解引入了ApolloConfigRegistrar类,该类负责配置的注册和加载。
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.TYPE})
@Documented
@Import({
ApolloConfigRegistrar.class})
public @interface EnableApolloConfig {
String[] value() default {
"application"};
int order() default Integer.MAX_VALUE;
}
核心方法解析
- registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)方法
- 作用:在Spring的应用上下文中注册与Apollo配置相关的Bean。
- 实现
public void registerBeanDefiniti