ITeye博客

spring cloud config实现datasource的热部署

m635674608 · 2017-11-21 16:44 · spring · 编程语言 · Markdown

关于spring cloud config的基本使用,前面的博客中已经说过了,如果不了解的话,请先看以前的博客

spring cloud config整合gitlab搭建分布式的配置中心

spring cloud config分布式配置中心的高可用

今天,我们的重点是如何实现数据源的热部署。

1、在客户端配置数据源

 

[java] view plain copy

 

  1. @RefreshScope
  2. @Configuration// 配置数据源
  3. public class DataSourceConfigure {
  4. @Bean
  5. @RefreshScope// 刷新配置文件
  6. @ConfigurationProperties(prefix="spring.datasource") // 数据源的自动配置的前缀
  7. public DataSource dataSource(){
  8. return DataSourceBuilder.create().build();
  9. }
  10. }

通过上面的几个步骤,就可以实现在gitlab上修改配置文件,刷新后,服务器不用重启,新的数据源就会生效。

 

2、自定义数据源的热部署

当我们使用spring boot集成druid,我们需要手动来配置数据源,代码如下:

 

[java] view plain copy

 

  1. package com.chhliu.springcloud.config;
  2. import java.sql.SQLException;
  3. import javax.sql.DataSource;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.cloud.context.config.annotation.RefreshScope;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.context.annotation.Primary;
  9. import com.alibaba.druid.pool.DruidDataSource;
  10. import lombok.extern.slf4j.Slf4j;
  11. /**
  12. *
  13. * 描述:如果不使用代码手动初始化DataSource的话,监控界面的SQL监控会没有数据("是spring boot的bug???")
  14. * @author chhliu
  15. * 创建时间:2017年2月9日 下午7:33:08
  16. * @version 1.2.0
  17. */
  18. @Slf4j
  19. @Configuration
  20. @RefreshScope
  21. public class DruidConfiguration {
  22. @Value("${spring.datasource.url}")
  23. private String dbUrl;
  24. @Value("${spring.datasource.username}")
  25. private String username;
  26. @Value("${spring.datasource.password}")
  27. private String password;
  28. @Value("${spring.datasource.driverClassName}")
  29. private String driverClassName;
  30. @Value("${spring.datasource.initialSize}")
  31. private int initialSize;
  32. @Value("${spring.datasource.minIdle}")
  33. private int minIdle;
  34. @Value("${spring.datasource.maxActive}")
  35. private int maxActive;
  36. @Value("${spring.datasource.maxWait}")
  37. private int maxWait;
  38. @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  39. private int timeBetweenEvictionRunsMillis;
  40. @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  41. private int minEvictableIdleTimeMillis;
  42. @Value("${spring.datasource.validationQuery}")
  43. private String validationQuery;
  44. @Value("${spring.datasource.testWhileIdle}")
  45. private boolean testWhileIdle;
  46. @Value("${spring.datasource.testOnBorrow}")
  47. private boolean testOnBorrow;
  48. @Value("${spring.datasource.testOnReturn}")
  49. private boolean testOnReturn;
  50. @Value("${spring.datasource.poolPreparedStatements}")
  51. private boolean poolPreparedStatements;
  52. @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
  53. private int maxPoolPreparedStatementPerConnectionSize;
  54. @Value("${spring.datasource.filters}")
  55. private String filters;
  56. @Value("${spring.datasource.connectionProperties}")
  57. private String connectionProperties;
  58. @Value("${spring.datasource.useGlobalDataSourceStat}")
  59. private boolean useGlobalDataSourceStat;
  60. @Bean     //声明其为Bean实例
  61. @Primary  //在同样的DataSource中,首先使用被标注的DataSource
  62. @RefreshScope
  63. public DataSource dataSource(){
  64. DruidDataSource datasource = new DruidDataSource();
  65. datasource.setUrl(this.dbUrl);
  66. datasource.setUsername(username);
  67. datasource.setPassword(password);
  68. datasource.setDriverClassName(driverClassName);
  69. //configuration
  70. datasource.setInitialSize(initialSize);
  71. datasource.setMinIdle(minIdle);
  72. datasource.setMaxActive(maxActive);
  73. datasource.setMaxWait(maxWait);
  74. datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  75. datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  76. datasource.setValidationQuery(validationQuery);
  77. datasource.setTestWhileIdle(testWhileIdle);
  78. datasource.setTestOnBorrow(testOnBorrow);
  79. datasource.setTestOnReturn(testOnReturn);
  80. datasource.setPoolPreparedStatements(poolPreparedStatements);
  81. datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  82. datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
  83. try {
  84. datasource.setFilters(filters);
  85. } catch (SQLException e) {
  86. log.error("druid configuration initialization filter: "+ e);
  87. }
  88. datasource.setConnectionProperties(connectionProperties);
  89. return datasource;
  90. }
  91. }

通过上面的示例,也可以实现数据源的动态刷新。接下来,我们就来看看,spring cloud config是怎么来实现数据源的热部署的。

 

从前面的博客中,我们不难发现,要想实现动态刷新,关键点就在post refresh的请求上,那我们就从刷新配置文件开始。

当我们post刷新请求的时候,这个请求会被actuator模块拦截,这点从启动的日志文件中就可以看出

 

[java] view plain copy

 

  1. Mapped "{[/refresh || /refresh.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.endpoint.GenericPostableMvcEndpoint.invoke()

接下来,我们就来看actuator定义的EndPoint,然后我们就找到了RefreshEndpoint这个类,该类的源码如下:

 

 

[java] view plain copy

 

  1. @ConfigurationProperties(prefix = "endpoints.refresh", ignoreUnknownFields = false)
  2. @ManagedResource
  3. public class RefreshEndpoint extends AbstractEndpoint<Collection<String>> {
  4. private ContextRefresher contextRefresher;
  5. public RefreshEndpoint(ContextRefresher contextRefresher) {
  6. super("refresh");
  7. this.contextRefresher = contextRefresher;
  8. }
  9. @ManagedOperation
  10. public String[] refresh() {
  11. Set<String> keys = contextRefresher.refresh();
  12. return keys.toArray(new String[keys.size()]);
  13. }
  14. @Override
  15. public Collection<String> invoke() {
  16. return Arrays.asList(refresh());
  17. }
  18. }

从上面的源码,我们可以看到,重点在ContextRefresher这个类上,由于这个类太长了,下面把这个类的部分源码贴出来:

 

 

[java] view plain copy

 

  1. private RefreshScope scope;
  2. public ContextRefresher(ConfigurableApplicationContext context, RefreshScope scope) {
  3. this.context = context;
  4. this.scope = scope;
  5. }
  6. public synchronized Set<String> refresh() {
  7. Map<String, Object> before = extract(
  8. this.context.getEnvironment().getPropertySources());// 1、before,加载提取配置文件
  9. addConfigFilesToEnvironment();// 2、将配置文件加载到环境中
  10. Set<String> keys = changes(before,
  11. extract(this.context.getEnvironment().getPropertySources())).keySet();// 3、替换原来环境变量中的值
  12. this.context.publishEvent(new EnvironmentChangeEvent(keys));// 4、发布变更事件,
  13. this.scope.refreshAll();
  14. return keys;
  15. }

从上面的代码不难看出,重点经历了4个步骤,上面代码中已标注。

 

http://blog.csdn.net/liuchuanhong1/article/details/75446850

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。