spring boot整合apollo

由于apollo是提供配置管理的服务,即项目的配置需要统一存放在apollo上进行管理。对于单体项目来说需要与apollo进行通信并获取项目本身需要的配置信息。所以我们需要使用apollo提供的客户端apollo-client用于配置的获取和装配,以下详细介绍整合的过程步骤。


Springboot整合apollo

1.在pom.xml中导入apollo-client.jar

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


        <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-context</artifactId>
           <version>2.0.1.RELEASE</version>
       </dependency>

2.    创建META-INF文件夹,在该文件夹中创建app.properties文件。

3.    在app.properties文件中添加app.id=     (您要拉去的配置中心项目的appid)

 

 

问题:apollo在这里写appid的意义?

答:用于apollo配置中心与应用本身拉去配置的识别,不至于拉去不需要的配置文件,apollo-client会默认读取/META-INF/app.properties文件中的app.id属性。注意:这里的app.id的值不能用引号括起来。

 

4.    在项目的yml文件中配置apollo配置集群内治的注册中心

1.dev config 获取dev环境的配置

apollo:
 meta: http://localhost:8080
 bootstrap:
   enabled: true
   eagerLoad:
     enabled: true
   namespaces: application,TEST1.curd-common

meta是apollo配置中心内置的注册中心地址。这里有dev、fat、uat、pro四个环境。分别对应的地址为:

  开发环境  dev:http://127.0.0.1:8080

  测试环境  fat:  http://127.0.0.1:8180

  渗透环境  uat:http://127.0.0.1:8280

生产环境  pro: http://127.0.0.1:8380

5.    打包发版本

打包发版的时候如何发?我本地测试和线上测试来回改,就比较太麻烦了。所以我们pom文件中设置打包的相关配置。

1.在编译的时候指定maven可以扫描到的文件夹。所以在<build>标签里添加资源路径。

  <resources>
           <resource>
               <directory>src/main/resources</directory>     //这里文件夹
               <filtering>true</filtering>     //过滤
                <includes>
                   <include>mapper/*.xml</include>  //将mybats生成的xml打入包内
                    <include>META-INF/*.properties</include>  //打入app.properties
                   <include>application.properties</include>  //打入项目的application
                   <include>static/**</include>       //打入静态资源
                   <include>templates/**</include>   //打入拦截器拦截的目录(index)
                </includes>
           </resource>
       </resources>

2.设置打包的配置

   <profiles>
       <profile>
           <id>dev</id>    
           <properties>
               <defaultApollo>http://127.0.0.1:8080</defaultApollo>
           </properties>
           <activation>
               <activeByDefault>true</activeByDefault>
           </activation>
       </profile>
       <profile>
           <id>fat</id>
           <properties>
                <defaultApollo>http://127.0.0.1:8180</defaultApollo>
           </properties>
       </profile>
       <profile>
           <id>uat</id>
           <properties>
               <defaultApollo>http://127.0.0.1:8280</defaultApollo>
           </properties>
       </profile>
       <profile>
           <id>pro</id>
           <properties>
               <defaultApollo>http://127.0.0.1:8380</defaultApollo>
           </properties>
       </profile>
</profiles>

6.    开启apollo服务

在启动类上添加注解:@EnableApolloConfig

 

7.    测试从apollo配置中心拉去的配置


1.编写获取apollo配置的controller

/**
 *apollo测试
 */
@RequestMapping(value ="/apollo")
@RestController
public class AolloTestController {
 
   @Value(value = "${application:获取私有配置失败}")
   private String application;
 
   @Value(value = "${common:获取共有配置失败}")
   private String common;
 
   //获取私有的application的配置
   @ApolloConfig(value = "application")
   private Config applicationConfig;
 
   //获取公共配置
   @ApolloConfig(value = "TEST1.curd-common")
   private Config commonConfig;
 
   /**
    * 测试获取到的apollo信息
    */
   @GetMapping(value = "/config")
   public StringBuffer getController() {
       StringBuffer stringBuffer=new StringBuffer();
       Set<String> properties =applicationConfig.getPropertyNames();
       for (String property : properties) {
           System.err.println(property + "=" +applicationConfig.getProperty(property,"123"));
           stringBuffer.append(property + "=" + applicationConfig.getProperty(property,"123")+"\n");
       }
       Set<String> commonProperties=commonConfig.getPropertyNames();
       commonProperties.forEach(key->{
           System.err.println(key+"="+commonConfig.getProperty(key,"1"));
           stringBuffer.append(key +"=" + commonConfig.getProperty(key,"3")+"\n");
       });
       return stringBuffer;
    }
 
}

2.启动项目

在浏览器中打开http://localhost:9001/apollo/config

测试apollo拉取配置中心的内容。

 

后台打印的配置信息:

获取apollo配置成功!

8.     修改配置文件热发布

测试配置对象得配置

@Data  //get、set
@RefreshScope   //必要,否则spring 容器刷新不了
@AllArgsConstructor   //必要的
@NoArgsConstructor   //必要的
@Configuration     //  加载到容器
@ConfigurationProperties(prefix = "com.test.demo")  
public class ApolloRefresh {
    private String wcfService;
    private String cnkiService;
}

9.     热发布监听

Apollo能通过长连接来监听配置文件得修改,并能发布到应用中,对一般得属性,apollo是热发布得,但是对对象类型得配置bean来说,需要刷新spring ioc容器。下面是该demo的热发布测试代码。

 
@Component
public class ContextApolloRefresh {
    /**
     * apollo配置更新时,刷新applicationcontext容器
     */
    private final RefreshScope refreshScope;
    /**
     * 注入测试,打印修改前后得配置
     */
    @Autowired
    private ApolloRefresh apolloRefresh;
    /**
     * 初始化刷新
     * @param refreshScope
     */
    public ContextApolloRefresh(RefreshScope refreshScope) {
        this.refreshScope = refreshScope;
    }
    /**
     * apollo配置监听
     * @param changeEvent
     */
    @ApolloConfigChangeListener(value = {"application", "TEST1.apollo"},interestedKeyPrefixes = {"net.cnki.demo"})
    public void onChange(ConfigChangeEvent changeEvent) {
        /**
         * 这是可以打印出刷新前读取配置
         */
        System.out.println(apolloRefresh.toString());
        refreshScope.refreshAll();
        System.out.println(apolloRefresh.toString());
        /**
         * 这里可以打印刷新后读取的配置
         */
    }
}


在apollo中修改配置之后,热发布前后打印的属性:

 


至此apollo整合的基本过程完毕,包含热发布和基本的配置内容,谢谢观看!

 

<think>好的,用户现在想了解Spring Cloud Alibaba如何整合Apollo。之前他们已经问过关于@ApolloConfigChangeListener注解的两个参数,现在可能是想进一步在实际项目中使用Apollo,特别是结合Spring Cloud Alibaba。 首先,我需要回忆Spring Cloud Alibaba和Apollo的关系。Spring Cloud Alibaba提供了一套微服务解决方案,包括配置管理,而Apollo是携程开源的配置中心。虽然Spring Cloud Alibaba默认支持Nacos作为配置中心,但用户可能希望用Apollo代替,或者需要整合两者。 接下来,用户可能想知道整合的具体步骤,比如依赖添加、配置设置、代码示例等。可能需要从创建项目开始,添加必要的依赖,比如apollo-client和spring-cloud-starter-alibaba-nacos-config(虽然Nacos是默认,但这里可能需要调整),不过实际上可能更直接使用ApolloSpring Boot Starter。 还需要考虑配置文件的内容,比如bootstrap.yml中配置Apollo的元数据,如app.id、meta地址等。另外,可能需要讲解如何启用Apollo,使用@EnableApolloConfig注解,或者在配置文件中设置apollo.bootstrap.enabled=true。 然后,用户可能需要知道如何动态更新配置,比如使用@ApolloConfigChangeListener监听配置变化,并刷新Spring的Environment,或者结合@RefreshScope。这部分需要详细说明,尤其是如何触发Bean的刷新。 此外,用户可能关心高级配置,比如命名空间、集群配置,以及如何与Spring Cloud的其他组件集成,比如Feign、Ribbon等。需要注意Spring Cloud Alibaba的版本兼容性,不同版本可能有不同的配置方式。 还要考虑到用户可能的误区,比如依赖冲突,或者配置未正确加载的问题。可能需要提醒检查依赖版本,确保Spring Cloud Alibaba和Apollo客户端的版本兼容,同时检查bootstrap.yml是否正确配置,是否启用了Apollo的引导过程。 最后,需要总结整合的关键点,强调配置的步骤和注意事项,帮助用户避免常见错误,确保整合顺利进行。</think>以下是 Spring Cloud Alibaba 整合 Apollo 的详细介绍: --- ### **1. 整合背景** Spring Cloud Alibaba 是阿里巴巴开源的微服务解决方案,提供了服务发现、配置管理等能力。虽然其默认集成 **Nacos** 作为配置中心,但通过扩展可以无缝对接 **Apollo**(携程开源的配置中心),实现配置的集中管理和动态更新。 --- ### **2. 整合步骤** #### **2.1 添加依赖** 在项目的 `pom.xml` 中引入 Apollo 客户端和 Spring Cloud Alibaba 依赖: ```xml <dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>1.9.0</version> <!-- 根据实际版本调整 --> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <!-- 需排除默认的 Nacos 配置管理(若不需要) --> </dependency> ``` #### **2.2 配置文件** 在 `bootstrap.yml` 或 `bootstrap.properties` 中配置 Apollo 元数据: ```yaml apollo: bootstrap: enabled: true # 启用 Apollo 配置 namespaces: application,redis.yml # 监听的命名空间(多个用逗号分隔) meta: http://apollo-config-service:8080 # Apollo Meta Server 地址 app: id: your-app-id # Apollo 中注册的应用 ID ``` #### **2.3 启用 Apollo 配置** 在 Spring Boot 启动类上添加注解 `@EnableApolloConfig`: ```java @SpringBootApplication @EnableApolloConfig // 启用 Apollo 配置管理 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` --- ### **3. 动态配置使用** #### **3.1 注入配置值** 通过 `@Value` 注解直接获取配置: ```java @RestController public class ConfigController { @Value("${db.url:default-url}") // 默认值可选项 private String dbUrl; } ``` #### **3.2 监听配置变更** 使用 `@ApolloConfigChangeListener` 监听配置变化,并触发 Spring 环境更新: ```java @Component public class ApolloConfigListener { @Autowired private RefreshScope refreshScope; // 监听指定命名空间和配置前缀 @ApolloConfigChangeListener( value = "application", interestedKeyPrefixes = {"db."} ) public void onConfigChange(ConfigChangeEvent event) { // 刷新带有 @RefreshScope 注解的 Bean refreshScope.refreshAll(); // 或处理具体配置变更逻辑 } } ``` #### **3.3 结合 @RefreshScope** 在需要动态更新的 Bean 上添加 `@RefreshScope`: ```java @RefreshScope @Component public class DynamicConfigBean { @Value("${log.level:info}") private String logLevel; } ``` --- ### **4. 高级配置** #### **4.1 命名空间与集群** - **命名空间**:通过 `apollo.bootstrap.namespaces` 指定多个命名空间(如 `application,redis.yml`)。 - **集群**:在 Apollo 控制台配置应用所属集群,或在配置文件中指定 `apollo.cluster`。 #### **4.2 本地缓存与灾备** - **本地缓存**:Apollo 会自动缓存配置到 `./opt/data/{appId}/config-cache` 目录,确保断网时可用。 - **灾备配置**:在 Apollo 控制台设置默认配置(`apollo-env.properties`),作为网络不可用时的后备方案。 --- ### **5. 整合注意事项** 1. **版本兼容性**:确保 Spring Cloud Alibaba 与 Apollo 客户端版本兼容(参考官方文档)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值