本文只贴相关代码段,完整代码请移步至本人github,若是喜欢,可以star给予支持

作者:cnJun

博客专栏:

https://www.cnblogs.com/cnJun/

本文实现目标

  • 重要的配置信息进行统一管理,例如数据库密码等。
  • 项目端口号、上下文等可以直接设置在配置中心
  • xml、properties、java、ftl文件可以轻松获取到配置中心的配置信息

前期工作

对于config_toolkit及zookeeper的安装及创建节点请自己查阅相关资料

config_toolkit初始配置可以参考https://github.com/dangdangdotcom/config-toolkit

具体实现

启动项设置

  1. -Dconfig.zookeeper.connectString=localhost:2181
  2. -Dconfig.rootNode=/project/module
  3. -Dconfig.version=1.0.0
  4. -Dconfig.groupName=sb2

其中

connectString为zookeeper的连接地址加端口号

rootNode为在zookeeper创建的根节点

version为版本号

groupName是你自己创建的组管理名称

导入相关jar包

  1. <dependency>
  2. <groupId>com.dangdang</groupId>
  3. <artifactId>config-toolkit</artifactId>
  4. <version>3.3.2-RELEASE</version>
  5. </dependency>

applicationContext.xml

在applicationContext.xml中引入config_toolkit的相关配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:c="http://www.springframework.org/schema/c"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
  6. default-lazy-init="true">
  7. <description>Spring公共配置</description>
  8. <bean id="configProfile" class="com.dangdang.config.service.zookeeper.ZookeeperConfigProfile">
  9. <constructor-arg name="connectStr"
  10. value="#{systemProperties['config.zookeeper.connectString']}" />
  11. <constructor-arg name="rootNode" value="#{systemProperties['config.rootNode']}" />
  12. <constructor-arg name="version" value="#{systemProperties['config.version']}" />
  13. </bean>
  14. <bean id="configGroupSources" class="com.dangdang.config.service.support.spring.ConfigGroupSourceFactory" factory-method="create">
  15. <constructor-arg name="configGroups">
  16. <list>
  17. <bean class="com.dangdang.config.service.zookeeper.ZookeeperConfigGroup" c:configProfile-ref="configProfile" c:node="#{systemProperties['config.groupName']}" c:enumerable="true" />
  18. <bean class="com.dangdang.config.service.zookeeper.ZookeeperConfigGroup" c:configProfile-ref="configProfile" c:node="apps_common" c:enumerable="true" />
  19. <bean class="com.dangdang.config.service.file.FileConfigGroup">
  20. <constructor-arg name="configProfile">
  21. <bean class="com.dangdang.config.service.file.FileConfigProfile">
  22. <constructor-arg name="fileEncoding" value="utf-8" />
  23. <constructor-arg name="contentType" value="properties" />
  24. </bean>
  25. </constructor-arg>
  26. <constructor-arg name="location" value="classpath:application.properties" />
  27. <constructor-arg name="enumerable" value="true"/>
  28. </bean>
  29. </list>
  30. </constructor-arg>
  31. </bean>
  32. <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
  33. <property name="order" value="1" />
  34. <property name="ignoreUnresolvablePlaceholders" value="true" />
  35. <property name="propertySources" ref="configGroupSources" />
  36. </bean>
  37. </beans>
  • 其中使用systemProperties获取的参数值为上面启动设置里面的值,这里可以根据自己的情况进行修改,可以直接赋值,也可以写在
  • application.properties里面获取
  • 配置中还引入了application.properties
  • 读取参数时是按照configGroups中的顺序来读取,所以会优先使用这里面前面组中所拥有的参数
  • 在xml中我们注入了configGroupSources的bean,我们后面主要从此bean中获取相关的数据

完成到这里,我们如果在配置中心配置了相关的server.portserver.contextPath,就已经可以修改启动时的端口号和上下文了

上下文工具文件 SpringContextUtil.java

此文件用于获取上面设置的configGroupSources

  1. package com.chenyingjun.springboot2.utils;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.NoSuchBeanDefinitionException;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.ApplicationContextAware;
  6. import org.springframework.context.annotation.Configuration;
  7. /**
  8. * 静态获取Bean
  9. *
  10. * @author chenyingjun
  11. * @version 2018年08月24日
  12. * @since 1.0
  13. *
  14. */
  15. @Configuration
  16. public class SpringContextUtil implements ApplicationContextAware {
  17. private static ApplicationContext applicationContext;
  18. /**
  19. * 重写上下文信息
  20. * @param applicationContext 上下文
  21. * @throws BeansException e
  22. */
  23. @Override
  24. public void setApplicationContext(ApplicationContext applicationContext)
  25. throws BeansException {
  26. SpringContextUtil.applicationContext = applicationContext;
  27. }
  28. /**
  29. * 获取上下文
  30. * @return 上下文
  31. */
  32. public static ApplicationContext getApplicationContext() {
  33. return applicationContext;
  34. }
  35. /**
  36. * 获取指定的bean
  37. * @param name bean名
  38. * @return bean对象
  39. * @throws BeansException e
  40. */
  41. public static Object getBean(String name) throws BeansException {
  42. try {
  43. return applicationContext.getBean(name);
  44. } catch (Exception e) {
  45. throw new RuntimeException("获取的Bean不存在!");
  46. }
  47. }
  48. public static <T> T getBean(String name, Class<T> requiredType)
  49. throws BeansException {
  50. return applicationContext.getBean(name, requiredType);
  51. }
  52. public static boolean containsBean(String name) {
  53. return applicationContext.containsBean(name);
  54. }
  55. public static boolean isSingleton(String name)
  56. throws NoSuchBeanDefinitionException {
  57. return applicationContext.isSingleton(name);
  58. }
  59. public static Class<? extends Object> getType(String name)
  60. throws NoSuchBeanDefinitionException {
  61. return applicationContext.getType(name);
  62. }
  63. public static String[] getAliases(String name)
  64. throws NoSuchBeanDefinitionException {
  65. return applicationContext.getAliases(name);
  66. }
  67. }

配置参数获取文件PropertiesLoaderUtil.java

  1. package com.chenyingjun.springboot2.utils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.core.env.MutablePropertySources;
  5. import org.springframework.core.env.PropertySource;
  6. import java.util.Iterator;
  7. import java.util.NoSuchElementException;
  8. /**
  9. * 配置参数信息
  10. * @author chenyingjun
  11. * @date 2018年8月24日
  12. */
  13. public class PropertiesLoaderUtil {
  14. /**
  15. * 日志
  16. */
  17. private static Logger logger = LoggerFactory.getLogger(PropertiesLoaderUtil.class);
  18. /**
  19. * properties
  20. */
  21. private MutablePropertySources propertySources;
  22. /**
  23. * 加载配置信息
  24. */
  25. public PropertiesLoaderUtil() {
  26. try {
  27. this.propertySources = (MutablePropertySources) SpringContextUtil.getBean("configGroupSources");
  28. } catch (Exception var3) {
  29. logger.error("没有配置统一配置服务");
  30. }
  31. }
  32. /**
  33. * 根据key值获取配置信息
  34. * @param key key
  35. * @return 配置信息
  36. */
  37. private String getValue(String key) {
  38. String systemProperty = System.getProperty(key);
  39. if (systemProperty != null) {
  40. return systemProperty;
  41. } else {
  42. if (this.propertySources != null) {
  43. Iterator iter = this.propertySources.iterator();
  44. while(iter.hasNext()) {
  45. PropertySource<?> str = (PropertySource)iter.next();
  46. if (str.containsProperty(key)) {
  47. return str.getProperty(key).toString();
  48. }
  49. }
  50. }
  51. return null;
  52. }
  53. }
  54. /**
  55. * 根据key值获取配置信息
  56. * @param key key
  57. * @return 配置信息
  58. */
  59. public String getProperty(String key) {
  60. String value = this.getValue(key);
  61. if (value == null) {
  62. throw new NoSuchElementException();
  63. } else {
  64. return value;
  65. }
  66. }
  67. /**
  68. * 根据key值获取配置信息
  69. * @param key key
  70. * @param defaultValue 默认值
  71. * @return 配置信息
  72. */
  73. public String getProperty(String key, String defaultValue) {
  74. String value = this.getValue(key);
  75. return value != null ? value : defaultValue;
  76. }
  77. }

使用于获取数据后全局使用的工具类GlobalUtil.java

  1. package com.chenyingjun.springboot2.utils;
  2. /**
  3. * 配置信息获取
  4. * @author chenyingjun
  5. * @date 2018年8月13日
  6. */
  7. public class GlobalUtil {
  8. /**
  9. * 配置参数信息
  10. */
  11. private static PropertiesLoaderUtil propertiesLoaderUtil;
  12. /**
  13. * 构建函数
  14. */
  15. public GlobalUtil() {
  16. }
  17. /**
  18. * 根据key值获取配置信息
  19. * @param key key
  20. * @return 配置信息
  21. */
  22. public static String getConfig(String key) {
  23. return getPropertiesLoaderUtil().getProperty(key);
  24. }
  25. /**
  26. * 根据key值获取配置信息
  27. * @param key key
  28. * @param defaultValue 默认值
  29. * @return 配置信息
  30. */
  31. public static String getConfig(String key, String defaultValue) {
  32. return getPropertiesLoaderUtil().getProperty(key, defaultValue);
  33. }
  34. public static int getIntConfig(String key) {
  35. return Integer.valueOf(getConfig(key)).intValue();
  36. }
  37. public static int getIntConfig(String key, int defaultValue) {
  38. return Integer.valueOf(getConfig(key, String.valueOf(defaultValue))).intValue();
  39. }
  40. public static boolean getBooleanConfig(String key) {
  41. return Boolean.valueOf(getConfig(key)).booleanValue();
  42. }
  43. public static boolean getBooleanConfig(String key, boolean defaultValue) {
  44. return Boolean.valueOf(getConfig(key, String.valueOf(defaultValue))).booleanValue();
  45. }
  46. public static long getLongConfig(String key) {
  47. return Long.valueOf(getConfig(key)).longValue();
  48. }
  49. public static long getLongConfig(String key, long defaultValue) {
  50. return Long.valueOf(getConfig(key, String.valueOf(defaultValue))).longValue();
  51. }
  52. /**
  53. * 加载配置文件
  54. * @return 配置信息
  55. */
  56. private static PropertiesLoaderUtil getPropertiesLoaderUtil() {
  57. if (null == propertiesLoaderUtil) {
  58. propertiesLoaderUtil = new PropertiesLoaderUtil();
  59. }
  60. return propertiesLoaderUtil;
  61. }
  62. }

config_toolkit数据使用范例

此时,我们可以自由的对配置中心里面的数据进行获取了

java类内获取参数示例

  1. @Value("${systemProfiles.title}")
  2. private String testConfigValue;
  1. String title = GlobalUtil.getConfig("systemProfiles.title", "无值");

properties文件获取参数示例

  1. spring.redis.host=${redis.host}
  2. spring.redis.port=${redis.port}

xml文件获取参数示例

  1. <constructor-arg index="2" value="${redis.port}" name="port" type="int"/>

freemarker获取参数

需在自行定义工具配置类MyFreeMarkerConfig.java

  1. package com.chenyingjun.springboot2.config;
  2. import com.chenyingjun.springboot2.utils.GlobalUtil;
  3. import freemarker.template.Configuration;
  4. import freemarker.template.TemplateModelException;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Component;
  9. import javax.annotation.PostConstruct;
  10. /**
  11. * FreeMarker工具类配置
  12. *
  13. * @author chenyingjun
  14. * @since 1.0
  15. * @version 2018年8月15日 chenyingjun
  16. */
  17. @Component
  18. public class MyFreeMarkerConfig {
  19. /** Logger */
  20. private final Logger logger = LoggerFactory.getLogger(MyFreeMarkerConfig.class);
  21. /** Configuration */
  22. @Autowired
  23. private Configuration freeMarkerConfiguration;
  24. /**
  25. * 配置工具类
  26. */
  27. @PostConstruct
  28. public void freemarkerConfig() {
  29. try {
  30. freeMarkerConfiguration.setSharedVariable("global", new GlobalUtil());
  31. } catch (TemplateModelException e) {
  32. logger.error(e.toString(), e);
  33. }
  34. }
  35. }

这样,我们就能在ftl页面中获取我们需要的参数了

freemarker文件获取参数示例

  1. ${global.getConfig("systemProfiles.title")?html}

springboot2 config_toolkit 并且设置全局获取数据GlobalUtil的更多相关文章

  1. 微信小程序云开发-云函数-数据库和云函数获取数据的区别

    一.数据库获取数据 1.1 数据库获取数据的写法 在本地创建的页面js文件中写代码 1.2 数据库获取数据返回数据限制20条 数据库获取数据,每次返回20条数据(数据库有108条数据) 1.3 数据库 ...

  2. DotNetBar 中 SuperGridControl 加载数据、获取数据、设置样式

    1.加载数据 构建列 //加载列 GridColumn gd = new GridColumn(); gd.Name = "第1"; gd.HeaderText = "第 ...

  3. vuex之仓库数据的设置与获取

    如果你之前使用过vue.js,你一定知道在vue中各个组件之间传值的痛苦,在vue中我们可以使用vuex来保存我们需要管理的状态值,值一旦被修改,所有引用该值的地方就会自动更新,那么接下来我们就来学习 ...

  4. jquery获取和设置表单数据

    1.需求 正好做到设置和获取表单数据的功能,做个整理 2.计划安排 3.计划实施 1.获取值 <!--1获取普通文本框的值--> <input type="text&quo ...

  5. 中小研发团队架构实践之生产环境诊断工具WinDbg 三分钟学会.NET微服务之Polly 使用.Net Core+IView+Vue集成上传图片功能 Fiddler原理~知多少? ABP框架(asp.net core 2.X+Vue)模板项目学习之路(一) C#程序中设置全局代理(Global Proxy) WCF 4.0 使用说明 如何在IIS上发布,并能正常访问

    中小研发团队架构实践之生产环境诊断工具WinDbg 生产环境偶尔会出现一些异常问题,WinDbg或GDB是解决此类问题的利器.调试工具WinDbg如同医生的听诊器,是系统生病时做问题诊断的逆向分析工具 ...

  6. 使用Vue.js和Axios从第三方API获取数据 — SitePoint

    更多的往往不是,建立你的JavaScript应用程序时,你会想把数据从远程源或消耗一个[ API ](https:/ /恩.维基百科.org /维基/ application_programming_ ...

  7. hive从查询中获取数据插入到表或动态分区

    Hive的insert语句能够从查询语句中获取数据,并同时将数据Load到目标表中.现在假定有一个已有数据的表staged_employees(雇员信息全量表),所属国家cnty和所属州st是该表的两 ...

  8. jQuery使用ajax跨域请求获取数据

    jQuery使用ajax跨域请求获取数据  跨域是我在日常面试中经常会问到的问题,这词在前端界出现的频率不低,主要原因还是由于安全限制(同源策略, 即JavaScript或Cookie只能访问同域下的 ...

  9. WCF+Restfull服务 提交或获取数据时数据大小限制问题解决方案

    近日在使用wcf的restfull架构服务时遭遇到了提交大数据的问题. 大数据包含两种情形: 1)单条数据量过大. 2)提交或获取的数据条数过多. 在测试时发现,默认设置下当单条JSON数据大于30K ...

随机推荐

  1. 【Windows】添加定时任务不执行

    [问题]windows定时任务不执行.在“所有程序->附件->系统工具->任务计划程序”中添加了定时调用“D:\sys_task\bugmanager\run.bat”脚本的任务计划 ...

  2. MybatisPlus使用介绍

    创建UserController测试类 package com.cppdy.controller; import org.apache.ibatis.session.RowBounds; import ...

  3. LeetCode(81): 搜索旋转排序数组 II

    Medium! 题目描述: 假设按照升序排序的数组在预先未知的某个点上进行了旋转. ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] ). 编写一个函数来判断给 ...

  4. js获取到的页面中的checkbox选中的项

    需求描述:列表第一列是checkbox name和value都是id 想通过复选框的勾选状态来获取id,在js中获取 js代码: var checkId=$("input[name='che ...

  5. 【splunk】按时间统计并找到异常值

    场景: 有长时间对多个端口访问的日志数据,每天对端口的访问量是稳定的.如果某一天对某个端口的访问量突然增加表示可能出现了问题.现在要通过splunk找到异常值. 思路: 统计每个端口每天的访问量.统计 ...

  6. hdu4612 卡cin e-DCC缩点

    /* 给定无向图,求加入一条边后最少剩下多少桥 */ #include<bits/stdc++.h> using namespace std; #define maxn 200005 #d ...

  7. 论文阅读笔记十三:The One Hundred Layers Tiramisu: Fully Convolutional DenseNets for Semantic Segmentation(FC-DenseNets)(CVPR2016)

    论文链接:https://arxiv.org/pdf/1611.09326.pdf tensorflow代码:https://github.com/HasnainRaz/FC-DenseNet-Ten ...

  8. ActiveMQ使用的设计模式

    注:接收不需要连接池,而发送需要连接池,是因为,接收在启动项目时就要注册监听,数目是固定的,而发送则会随着时间数目不断在变动,需要连接池,性能更优. 重点代码: private static void ...

  9. Ajax增删改查-----------增

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. python基础知识之zip

    names =['zhangning','lsl','lyq','xww']age = [1,2,3,4]for a,b in zip(names,age): print(a,b)S = 'abcde ...