您的位置:首页 > 编程语言 > Java开发

基于mysql的spring cloud config server

2017-11-14 15:47 387 查看
前言:由于项目已经拆分为模块化,每一个项目都存在相同的配置文件,比如数据库 redis 等。上线需要修改相关的配置信息,以前也用到过spring profile。总感觉用的不太舒服,最近在逛CSDN 时看到有很多同行在用spring cloud config 来统一管理配置文件,觉得是个不错的方案。

简单介绍下,本次我的配置文件是存放在数据库中的,而不是放在svn 或者 git 上面,大家可以几种方式都试一下,选出最合适的一种就好了,那么这些都没什么问题了 可以试试eureka 来做个高可用的方案。

首先说下config-server 项目,是spring boot ,由于是基于mysql 那么用mybatis 或者 原生的 jdbc 或者 spring 的 jdbctemplete 都可以,看各位的选择。

数据库表结构:

CREATE TABLE `cloud_config` (

  `cloud_config_id` int(32) NOT NULL AUTO_INCREMENT COMMENT '主键',

  `cloud_config_name` varchar(100) NOT NULL COMMENT '应用名,GLOBAL为全局',

  `cloud_config_key` varchar(100) NOT NULL COMMENT '属性名',

  `cloud_config_desc` varchar(255) NOT NULL COMMENT '参数描述',

  `cloud_config_dev_value` varchar(255) DEFAULT NULL COMMENT '开发环境值',

  `cloud_config_test_value` varchar(255) DEFAULT NULL COMMENT '测试环境值',

  `cloud_config_prod_value` varchar(255) DEFAULT NULL COMMENT '正式环境值',

  PRIMARY KEY (`cloud_config_id`)

) ENGINE=InnoDB AUTO_INCREMENT=154 DEFAULT CHARSET=utf8 COMMENT='系统环境变量配置表';

实体类:

public class CloudConfig{

private String CloudConfigId;
private String CloudConfigName;
private String CloudConfigKey;
private String CloudConfigDesc;
private String CloudConfigDevValue;
private String CloudConfigTestValue;
private String CloudConfigProdValue;

setter getter 方法省略....

mapper.xml:

<select id="selectByprofile" parameterType="java.lang.String" resultMap="BaseResultMap">

    SELECT 

    DISTINCT

    <include refid="Base_Column_List"/>

    FROM 

    cloud_config

    WHERE

    cloud_config_name = #{name}

  </select>

这里简单提供下SQL 语句就OK 了,我相信做过mybatis 项目的  其他部分不用多少,那么也就省下了dao层接口 以及 servier 接口,下面奉上 service impl 的代码

 @Service

public class EnvironmentPropertiesService {

private final Logger LOG = LoggerFactory.getLogger(EnvironmentPropertiesService.class);

@Autowired
private CloudConfigMapper applicationConfigMapper;

@Transactional
public Map<String, String> get(String applicationName, String profile) {
List<CloudConfig> list = applicationConfigMapper
.selectByprofile(applicationName);
for (CloudConfig cloudConfig : list) {
LOG.info("应用名["+applicationName+"]-环境["+profile+"]-"+"属性值:"+cloudConfig.getCloudConfigDevValue());
}
System.out.println();
Map<String, String> result = null;
if (list != null && list.size() > 0) {
result = new HashMap<String, String>();
for (CloudConfig cc : list) {
if (Objects.equals("test", profile)) {
result.put(cc.getCloudConfigKey(),
cc.getCloudConfigTestValue());
} else if (Objects.equals("prod", profile)) {
result.put(cc.getCloudConfigKey(),
cc.getCloudConfigProdValue());
} else if (Objects.equals("dev", profile)) {
result.put(cc.getCloudConfigKey(),
cc.getCloudConfigDevValue());
}
}
}
return result;
}

}

还有两个非常重要的类,相信大家在搜索spring cloud config 基于mysql 的时候 都会出现这2个类

“”DatabasesRepositoryConfiguration“”“”DatabasesEnvironmentRepository“”

下面给出这2个类的代码:

@Configuration

@ConditionalOnMissingBean({EnvironmentRepository.class})

@ConditionalOnProperty("spring.cloud.config.server.databases")

public class DatabasesRepositoryConfiguration {

@Autowired

    private ConfigurableEnvironment environment;

    @Bean

    public SearchPathLocator searchPathLocator() {

        return new NativeEnvironmentRepository(environment);

    }

    @Bean

    @Primary

    public EnvironmentRepository openEnvironmentRepository() {

        return new DatabasesEnvironmentRepository();

    }

}

public class DatabasesEnvironmentRepository implements EnvironmentRepository {
private static final Logger LOG = LoggerFactory.getLogger(DatabasesEnvironmentRepository.class);
@Autowired
private EnvironmentPropertiesService environmentPropertiesService;

public Environment findOne(String application,String profile,String lable) {
if(StringUtils.isEmpty(application)||StringUtils.isEmpty(profile)) return null;
Map<String,String>properties = environmentPropertiesService.get(application, profile);
if(properties!=null){
Environment environment = new Envi
be3e
ronment(application, new String[]{profile}, lable, "1.0");
 
environment.add(new PropertySource("application.properties",properties));
return environment;
}
return new Environment(application,profile);
}

}

好了,你的项目是spring boot 的   启动

@SpringBootApplication

@EnableConfigServer

public class StartSpringBootMain {

    public static void main(String[] args) throws Exception {

    SpringApplication springApplication =new SpringApplication(StartSpringBootMain.class);

        springApplication.run(args);

    }

}

还有一点差点忘了,就是要在你项目application.properties 文件中添加一条

spring.cloud.config.server.databases=true

现在开始测试下到底有没有OK ,怎么指定环境去查询相应的数据
http://192.168.1.122:8090/服务名/dev/
说明一下上面的URL ,前面是你启动config-server 的服务器IP 本地用localhost 或者127.0.0.1 后面是config-server 的端口,后面的都用中文说明了  dev 代表开发环境 这个dev 是在 service impl 代码中有去查询,然后结合SQL 去看下是怎么一个流程。

如果看到下面的结果 那么代表成功了

{"name":"jfk-invest-dl-service","profiles":["dev"],"label":null,"version":"1.0","propertySources":[{"name":"application.properties","source":{"spring.datasource.dbcp2.initial-size":"6","spring.datasource.username":"root","MANGER_URL":"http://192.168.1.135:800","spring.datasource.url":"jdbc:mysql://192.168.1.120:3306/jfkg-dev?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true","dubbo.application.name":"jfk-invest-dl-service","spring.datasource.dbcp2.max-total":"6","USER_SALT":"GtNc2WamlP","mybatis.config-location":"classpath:mybatis/mybatis.cfg.xml","spring.datasource.password":"123456","dubbo.application.timeout":"10000","spring.application.name":"jfk-invest-dl-service","dubbo.port":"9011","CONTEXT_NAME":"SMPMS","spring.mvc.throw-exception-if-no-handler-found":"true","mybatis.mapper-locations":"classpath:mapping/**/*.xml","spring.datasource.dbcp2.min-idle":"6","server.port":"8081","spring.datasource.dbcp2.max-wait-millis":"200","spring.datasource.driver-class-name":"com.mysql.jdbc.Driver","spring.datasource.type":"com.alibaba.druid.pool.DruidDataSource","dubbo.registry.address":"192.168.1.124:2181"}}]}


这第一部分是完成了,那么怎么去使用这部分数据了,由于我是部署在linux服务器上面 ,需要获取数据的服务 不管是打成jar 包运行 或者是 war 包 运行,指定环境变量即可,下面奉上:

jar 运行:

java -jar  xxxx.jar --spring.application.name=service --spring.cloud.config.profile=dev --spring.cloud.config.uri=http://192.168.1.122:8090/ 

war 运行:

这里需要修改一下catalina.sh,在差不多232行 加入 

JFK_OPTS="-Dspring.application.name=web -Dspring.cloud.config.profile=dev -Dspring.cloud.config.uri=http://192.168.1.122:8090/"

JAVA_OPTS="$JAVA_OPTS $JFK_OPTS"

启动的时候 回去调用这些数据。

下次会奉上 spring cloud config + eureka 做高可用,大家对上面的 还有理解不了的 或者有困难的,可以加QQ:993610778 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: