Spring Cloud Apollo 实践

接上一篇Windows下安装Apollo的常见问题,安装完毕后试着看怎么来使用一下。

 

首先到管理页面创建一个新的应用:

 

创建成功后会自动跳转到应用的维护界面,如下图所示:

 

 新增一个配置信息来进行后续的验证,添加成功后右上角弹出提示如需生效请发布,同时新增的配置项发布状态也是未发布,如下图中箭头指向以及框出的区域所示:

 

接下来随便找个Spring Cloud的工程,首先在pom中添加Apollo的依赖:

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

 

application.yml中添加Apollo相关的配置信息以及用来验证的配置项:

# Apollo 相关配置
app:
  id: spring-cloud-application # 与 Apollo 配置中心中的 AppId 一致

apollo:
  meta: http://localhost:8080 # Apollo 中的 Eureka 注册中心地址
  #cluster:  # 指定 Apollo 集群,相同集群实例使用对应集群的配置
  #cacheDir:  # 配置缓存目录,网络不可用时任然可提供配置服务
  bootstrap:
    enable: true # 启用 apollo

env: DEV # 指定环境

date: 20210903

 

添加对应到配置信息的配置类:

@Component
@ConfigurationProperties
public class ConfigProperties {

    @Value("${date}")
    private Integer date;

    public Integer getDate() {
        return date;
    }
}

同时在Controller层尝试获取该配置信息:

@RestController
@RequestMapping("/query")
public class ServiceController {

    @Autowired
    private ConfigProperties configProperties;

    @GetMapping("/getDate")
    public Integer getDate() {
        return configProperties.getDate();
    }
}

启动类中添加注解@EnableApolloConfig后便可以启动验证:

不过仔细观察启动信息,发现控制台有输出如下报错信息,应该是由于配置中心之前添加的配置项还未发布引起的:

2021-09-04 15:47:45.883  WARN 15804 --- [figRepository-1] c.c.f.a.i.RemoteConfigRepository         : Load config failed, will retry in 1 SECONDS. appId: spring-cloud-application, cluster: default, namespaces: application
2021-09-04 15:47:46.893  WARN 15804 --- [figRepository-1] c.c.f.a.i.AbstractConfigRepository       : Sync config failed, will retry. Repository class com.ctrip.framework.apollo.internals.RemoteConfigRepository, reason: Load Apollo Config failed - appId: spring-cloud-application, cluster: default, namespace: application, url: http://160.18.15.177:8080/configs/spring-cloud-application/default/application?ip=160.18.15.177&messages=%7B%22details%22%3A%7B%22spring-cloud-application%2Bdefault%2Bapplication%22%3A1%7D%7D [Cause: [status code: 404] Could not find config for namespace - appId: spring-cloud-application, cluster: default, namespace: application, please check whether the configs are released in Apollo!]

 

这时我们在Apollo的配置中心对之前创建的配置项进行发布:

发布成功后看到客户端应用的控制台有如下信息打印:

2021-09-04 15:50:28.360  INFO 15804 --- [Apollo-Config-1] c.f.a.s.p.AutoUpdateConfigChangeListener : Auto update apollo changed value successfully, new value: 20210904, key: date, beanName: configProperties, field: provider.config.ConfigProperties.date

再看看这时获取到的日期配置是否改变:

成功刷新,并且这时如果重新启动客户端应用会发现上一次从配置中心同步配置的报错也不再输出了。

 

 

参考资料:

https://www.cnblogs.com/mrhelloworld/p/apollo1.html

posted on 2021-09-04 16:00  DluT_eDdy  阅读(585)  评论(0编辑  收藏  举报

导航