springboot 整合 apollo

springboot 整合 apollo


添加jar包 maven引用

添加apollo 配置中心依赖

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

添加apollo配置

application.yml 文件中增加apollo配置

apollo:
  meta: http://IP:8080
  bootstrap:
    enabled: true
    namespaces: application,test
app:
  id: videostruct
  • app.id: 在apollo中,创建项目的AppId
  • meta : 在apollo的demo.sh文件配置的config_server_url地址
  • namespaces 配置中心命名空间
  • 如图

读取apollo配置文件内容


方式1

添加注解 EnableApolloConfig

读配置节点 :

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

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

@RequestMapping("/apollo")
public String apollo() {
    return "value " + name +  ",test" + test;
}

方式2

添加读取配置文件类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "liu")
@RefreshScope
@Data
public class DevConfig {
    private String name;
}
  • ConfigurationProperties中的prefix 是配置节点key的前缀,可以查询liu.xxxx所有数据
  • name 是属性值

使用方法

@Resource
DevConfig devConfig;

@RequestMapping("/apollo")
public String apollo() {
    return  "devConfig:" + devConfig.getName();
}

请求接口正常返回配置中心中的数据,但当修改配置中心中的数据时,此接口的值没有任何变动

此时增加 RefreshScope

先引用maven包,使用刷新配置注解

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

刷新config文件

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ConfigRefresh {
@Resource
private DevConfig devConfig;

@Resource
private RefreshScope refreshScope;

@ApolloConfigChangeListener("application")
public void onChange(ConfigChangeEvent changeEvent) {
    boolean configChange = false;
    for (String ckey : changeEvent.changedKeys()) {
        if (ckey.startsWith("liu")) {
            configChange = true;
            break;
        }
    }
    if (!configChange) {
        return;
    }

    refreshScope.refresh("devConfig");
 }
}
  • 此时liu开头的所有配置节点发生变化时,项目中也会实时更新

建议使用方法一读取,简单方便,实时刷新

posted @ 2021-12-18 19:10  未知_Master  阅读(327)  评论(0)    收藏  举报