携程官网对apollo的使用讲解了很多种方式的使用,但是感觉一些细节还是没讲全,特别是eureka配置中心地址的配置

这里对springboot整合apollo说一下

>SpringBoot启动vm参数添加:
-Ddev_meta=http://18.16.200.107:8080 -Denv=DEV
其中-Ddev-meta连接的是配置管理eureka的url地址
-Denv配置的是具体的环境

>也可以在C:\opt\settings\server.properties中添加环境配置:
env=DEV
这个配置文件里面只能配置环境,不能配置url

>第一步配置app.id,在META-INF/app.properties里面添加app.id,类型字符串

代码:

  1. package com.qhong.springboot;
  2.  
  3. import com.ctrip.framework.apollo.Config;
  4. import com.ctrip.framework.apollo.model.ConfigChange;
  5. import com.ctrip.framework.apollo.model.ConfigChangeEvent;
  6. import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
  7. import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
  8. import lombok.ToString;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.boot.context.properties.ConfigurationProperties;
  11. import org.springframework.stereotype.Component;
  12.  
  13. /**
  14. * 使用Java Config方式
  15. * 使用@ApolloConfig自动注入Config对象
  16. * 使用@ApolloConfigChangeListener自动注入ConfigChangeListener对象
  17. * 当监听到属性值发生变化后使用Config API修改属性值
  18. */
  19. @ToString
  20. @Component
  21. @ConfigurationProperties
  22. public class JavaConfigSample {
  23. /**
  24. * @ApolloConfig用来自动注入Config对象
  25. */
  26. @ApolloConfig
  27. private Config config;
  28. /**
  29. * @ApolloConfigChangeListener用来自动注册ConfigChangeListener
  30. */
  31. @ApolloConfigChangeListener
  32. private void someOnChange(ConfigChangeEvent changeEvent) {
  33. changeEvent.changedKeys().forEach(key ->{
  34. ConfigChange change = changeEvent.getChange(key);
  35. System.out.println(String.format("Found JavaConfigSample change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
  36. });
  37. }
  38.  
  39. @Value("${timeout:100}")
  40. private int timeout;
  41. private int batch;
  42.  
  43. @Value("${batch:200}")
  44. public void setBatch(int batch) {
  45. this.batch = batch;
  46. }
  47.  
  48. public int getTimeout() {
  49. if(config!=null) {
  50. return config.getIntProperty("timeout", );
  51. }else{
  52. return timeout;
  53. }
  54. }
  55.  
  56. public int getBatch() {
  57. return this.batch;
  58. }
  59. }

这个类里面timeout获取值的方式直接调用getIntProperty

  1. package com.qhong.springboot;
  2.  
  3. import com.ctrip.framework.apollo.Config;
  4. import com.ctrip.framework.apollo.model.ConfigChange;
  5. import com.ctrip.framework.apollo.model.ConfigChangeEvent;
  6. import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
  7. import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
  8. import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
  9. import com.google.common.collect.Lists;
  10. import com.google.common.collect.Maps;
  11. import java.util.List;
  12. import java.util.Map;
  13. import javax.annotation.PostConstruct;
  14. import lombok.AllArgsConstructor;
  15. import lombok.Builder;
  16. import lombok.Data;
  17. import lombok.NoArgsConstructor;
  18. import lombok.ToString;
  19. import org.springframework.boot.context.properties.ConfigurationProperties;
  20. import org.springframework.stereotype.Component;
  21.  
  22. /**
  23. * 使用Spring Boot ConfigurationProperties方式
  24. * <pre>
  25. * redis.cache.enabled = true
  26. * redis.cache.expireSeconds = 100
  27. * redis.cache.clusterNodes = 1,2
  28. * redis.cache.commandTimeout = 50
  29. * redis.cache.someMap.key1 = a
  30. * redis.cache.someMap.key2 = b
  31. * redis.cache.someList[0] = c
  32. * redis.cache.someList[1] = d
  33. * </pre>
  34. */
  35. @Data
  36. @Builder
  37. @ToString
  38. @NoArgsConstructor
  39. @AllArgsConstructor
  40. @Component
  41. @ConfigurationProperties(prefix = "redis.cache")
  42. @EnableApolloConfig("application")
  43. public class ConfigurationPropertiesSample {
  44.  
  45. private int expireSeconds;
  46. private String clusterNodes;
  47. private int commandTimeout;
  48.  
  49. private Map<String, String> someMap = Maps.newLinkedHashMap();
  50. private List<String> someList = Lists.newLinkedList();
  51.  
  52. @PostConstruct
  53. private void initialize() {
  54. System.out.println(String.format(
  55. "SampleRedisConfig initialized - expireSeconds: {}, clusterNodes: {}, commandTimeout: {}, someMap: {}, someList: {}",
  56. expireSeconds, clusterNodes, commandTimeout, someMap, someList));
  57. }
  58.  
  59. /**
  60. * @ApolloConfig用来自动注入Config对象
  61. */
  62. @ApolloConfig("application")
  63. private Config config;
  64. /**
  65. * @ApolloConfigChangeListener用来自动注册ConfigChangeListener
  66. */
  67. @ApolloConfigChangeListener("application")
  68. private void someOnChange(ConfigChangeEvent changeEvent) {
  69. changeEvent.changedKeys().forEach(key ->{
  70. ConfigChange change = changeEvent.getChange(key);
  71. System.out.println(String.format("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
  72. });
  73. }
  74. }

这个是各种属性类型的使用

apollo配置中心文本格式:

  1. esb.app.url = http://18.16.200.10:3000/
  2. endpoints.shutdown.enabled = true
  3. endpoints.shutdown.sensitive = false
  4. spring.http.multipart.maxFileSize = 100Mb
  5. spring.http.multipart.max-request-size = 100Mb
  6.  
  7. timeout =
  8. batch =
  9. redis.cache.enabled = false
  10. redis.cache.expireSeconds =
  11. redis.cache.clusterNodes = ,,,
  12. redis.cache.commandTimeout =
  13. redis.cache.someMap.key1 = a
  14. redis.cache.someMap.key2 = b
  15. redis.cache.someList[] = c
  16. redis.cache.someList[] = d

上面两种都是默认的namespace,为application

下面添加一个datasource命名空间类型的类

  1. package com.qhong.springboot;
  2.  
  3. import com.ctrip.framework.apollo.Config;
  4. import com.ctrip.framework.apollo.model.ConfigChange;
  5. import com.ctrip.framework.apollo.model.ConfigChangeEvent;
  6. import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
  7. import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
  8. import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
  9. import lombok.Data;
  10. import lombok.ToString;
  11. import org.springframework.boot.context.properties.ConfigurationProperties;
  12. import org.springframework.stereotype.Component;
  13.  
  14. /**
  15. * Created by qhong on 2018/5/8 16:10
  16. **/
  17. @ToString
  18. @Component
  19. @Data
  20. @ConfigurationProperties
  21. @EnableApolloConfig("datasource")
  22. public class DataSourceConfig {
  23. // 动态配置从esb config读取
  24. private String url;
  25. private String username;
  26. private String password;
  27. private String driverClassName;
  28.  
  29. /**
  30. * @ApolloConfig用来自动注入Config对象
  31. */
  32. @ApolloConfig("datasource")
  33. private Config config;
  34.  
  35. /**
  36. * @ApolloConfigChangeListener用来自动注册ConfigChangeListener
  37. */
  38. @ApolloConfigChangeListener("datasource")
  39. private void someOnChange(ConfigChangeEvent changeEvent) {
  40. changeEvent.changedKeys().forEach(key ->{
  41. ConfigChange change = changeEvent.getChange(key);
  42. System.out.println(String.format("Found datasource change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
  43. });
  44. }
  45.  
  46. }

注意EnableApolloConfig中定义datasource命名空间

上面类的具体文本:

  1. url = jdbc:mysql://120.26.130.187:3306/huishi-server?useUnicode=true&characterEncoding=utf-8&useSSL=false
  2. username = root
  3. password = jsy2016memeda
  4. driverClassName = com.mysql.jdbc.Driver

当然也可以使用ApolloConfig这个定义datasource命名空间的,然后一个个getProperty来获取值,就是有点不方便。

下面使用SpringBoot启动:

  1. package com.qhong.springboot;
  2.  
  3. import com.google.common.base.Charsets;
  4. import com.google.common.base.Strings;
  5. import java.io.BufferedReader;
  6. import java.io.InputStreamReader;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8. import org.springframework.boot.builder.SpringApplicationBuilder;
  9. import org.springframework.context.ApplicationContext;
  10. import org.springframework.web.bind.annotation.RestController;
  11.  
  12. @RestController
  13. @SpringBootApplication(scanBasePackages = {"com.qhong.springboot"})
  14. public class Application {
  15. public static void main(String[] args) throws Exception {
  16. ApplicationContext context = new SpringApplicationBuilder(Application.class).run(args);
  17. JavaConfigSample javaConfigSample = context.getBean(JavaConfigSample.class);
  18. ConfigurationPropertiesSample configurationPropertiesSample=context.getBean(ConfigurationPropertiesSample.class);
  19. DataSourceConfig dataSourceConfig=context.getBean(DataSourceConfig.class);
  20. System.out.println("Application Demo. Input any key except quit to print the values. Input quit to exit.");
  21. while (true) {
  22. System.out.print("> ");
  23. String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine();
  24. if (!Strings.isNullOrEmpty(input) && input.trim().equalsIgnoreCase("quit")) {
  25. System.exit();
  26. }
  27.  
  28. if(javaConfigSample!=null){
  29. System.out.println(javaConfigSample.toString());
  30. }
  31. if(configurationPropertiesSample!=null){
  32. System.out.println(configurationPropertiesSample.toString());
  33. }
  34. if(dataSourceConfig!=null){
  35. System.out.println(dataSourceConfig);
  36. }
  37.  
  38. }
  39. }
  40. }

随便输入字符就可以显示监控的字段

上面代码的地址:

https://gitee.com/hongdada/spring-boot-apollo-sample

https://blog.csdn.net/hry2015/article/details/72353994

https://blog.csdn.net/hry2015/article/details/72453920

参考:

https://github.com/ctripcorp/apollo/wiki/Java%E5%AE%A2%E6%88%B7%E7%AB%AF%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97

SpringBoot 整合携程Apollo配置管理中心的更多相关文章

  1. Spring Boot 2.0 整合携程Apollo配置中心

    原文:https://www.jianshu.com/p/23d695af7e80 Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境.不同集群的配置,配置修改后能够 ...

  2. 携程Apollo配置中心架构深度剖析

    转自:http://www.uml.org.cn/wfw/201808153.asp 一.介绍 Apollo(阿波罗)[参考附录]是携程框架部研发并开源的一款生产级的配置中心产品,它能够集中管理应用在 ...

  3. 携程 Apollo 配置中心传统 .NET 项目集成实践

    官方文档存在的问题 可能由于 Apollo 配置中心的客户端源码一直处于更新中,导致其相关文档有些跟不上节奏,部分文档写的不规范,很容易给做对接的新手朋友造成误导. 比如,我在参考如下两个文档使用传统 ...

  4. 携程apollo配置中心服务端如何感知配置更新?

    引言 前面有写过一篇<分布式配置中心apollo是如何实时感知配置被修改>,也就是客户端client是如何知道配置被修改了,有不少读者私信我你既然说了client端是如何感知的,那服务端又 ...

  5. 携程apollo系列-客户端集成

    本文讲解如何在 Java 程序中集成 Apollo 配置, 主要涉及到一些基础用法. 对于一些高级用法, 比如如何加密/解密配置项 (可用于数据库密码配置), 如何动态切换数据源地址,如何动态切换日志 ...

  6. 分布式配置中心 携程(apollo)

    1.传统配置文件与分布式配置文件区别 传统配置文件:如果修改了配置文件,需要重新打包发布,重新发布服务,而且每个环境的变更配置文件,比较繁琐. 分布式配置文件:将配置文件注册到配置中心上去,可以使用分 ...

  7. 携程apollo系列-个人开发环境搭建

    本博客讲详细讲解如何在 Windows 搭建携程 Apollo 服务器 (用户个人开发). 开发服务器有多种搭建方式:(1) docker, 搭建过程非常简单, 推荐有 docker 环境(2) 部署 ...

  8. 携程Apollo统一配置中心的搭建和使用

    原文链接:https://blog.csdn.net/luhong327/article/details/81453001 一.Apollo配置中心介绍 1.What is Apollo 1.1 Ap ...

  9. CentOS 7 搭建基于携程Apollo(阿波罗)配置中心单机模式

    Apollo(阿波罗)是携程框架部门研发的配置管理平台,能够集中化管理应用不同环境.不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限.流程治理等特性.服务端基于Spring Boot ...

随机推荐

  1. HTML5特性&&canvas

    1.HTML5是由W3C(万维网联盟,专注于XHTML 2.0)和WHATWG(专注于web表单和应用程序)共同合作的结果,2014年10月完成标准制定! 主要设计目的:为了在移动设备上支持多媒体. ...

  2. hdu2295DLX重复覆盖+二分

    题目是说 给了n个城市 m个雷达 你只能选择其中的k个雷达进行使用 你可以设置每个雷达的半径,最后使得所有城市都被覆盖,要求雷达的半径尽可能的小(所有雷达的半径是一样的) 二分最小半径,然后每次重新建 ...

  3. 【转】Spotlight实时监控Windows Server 2008

    Windows Server 2008作为服务器平台已逐渐被推广和应用,丰富的功能和良好的稳定性为其赢得了不错的口碑.但是和Windows Server 2003相比,其系统的自我监控功能并没有多大的 ...

  4. 【2017-03-23】CSS基础:内联样式

    CSS:层叠式样式表 1.对层标签整体进行操作 <div style="width:200px;height:200px;background-color:blue"> ...

  5. CAN学习网站

    百度搜索:Controller Area Network http://www.esd-electronics-usa.com/Controller-Area-Network-CAN-Introduc ...

  6. Codeforce 791A - Bear and Big Brother

    Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. ...

  7. [转载]Oracle中的NVL函数

    Oracle中函数以前介绍的字符串处理,日期函数,数学函数,以及转换函数等等,还有一类函数是通用函数.主要有:NVL,NVL2,NULLIF,COALESCE,这几个函数用在各个类型上都可以. 下面简 ...

  8. python-数据分析与展示(Numpy、matplotlib、pandas)---1

    笔记内容整理自mooc上北京理工大学嵩天老师python系列课程数据分析与展示,本人小白一枚,如有不对,多加指正 1.ndarray对象的属性 .ndim..shape..size(元素个数,不是占用 ...

  9. redis安装--转

    第一部分:安装redis 希望将redis安装到此目录 1 /usr/local/redis 希望将安装包下载到此目录 1 /usr/local/src 那么安装过程指令如下: 1 2 3 4 5 6 ...

  10. 原生Ajax和jqueryAjax写法

    原生写法: $('#send').click(function(){ //请求的5个阶段,对应readyState的值 //0: 未初始化,send方法未调用: //1: 正在发送请求,send方法已 ...