Springboot 实现前台动态配置数据源 (修改数据源之后自动重启)

1.将 db.properties 存放在classpath路径;

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ceshi?useUnicode=true&characterEncoding=utf8
username=root
password=root

2.使用Bean的方式配置 dataSource

package com.shulipeng.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.shulipeng.AutocodeApplication;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author shulipeng
 * @Description:
 * @date 2018/4/2
 */
@Configuration
public class DataSourceConfig {

    private static Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);

    //数据库类型
    private String dbType;

    @Bean(name = "dataSource")
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        try {
            PropertiesConfiguration properties = new PropertiesConfiguration("db.properties");
            String driverClassName = properties.getString("driverClassName");
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(properties.getString("url"));
            dataSource.setUsername(properties.getString("username"));
            dataSource.setPassword(properties.getString("password"));

            //判断数据库类型
            if(driverClassName.contains(Constant.DB_TYPE_MYSQL)){
                this.setDbType(Constant.DB_TYPE_MYSQL);
            }else if(driverClassName.contains(Constant.DB_TYPE_ORACLE)){
                this.setDbType(Constant.DB_TYPE_ORACLE);
            }

        } catch (ConfigurationException e) {
            logger.error("获取数据库配置文件失败" + e);
        }

        return dataSource;
    }

    /**
     * 动态修改数据库链接
     */
    public void changeDataSource () {
        Thread restartThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    AutocodeApplication.restart();
                } catch (InterruptedException ignored) {
                }
            }
        });
        restartThread.setDaemon(false);
        restartThread.start();
    }

    public String getDbType() {
        return dbType;
    }

    public void setDbType(String dbType){
        this.dbType = dbType;
    }
}

3.定义一个前台改变数据库配置文件并且重启的方法

  /**
     * 动态修改数据库地址,并且重新启动应用
     * @param dbMap
     * @return
     */
    @PostMapping("/db/update")
    @ResponseBody
    R changeDB(@RequestParam Map dbMap){
        try {
            PropertiesConfiguration conf = new PropertiesConfiguration("db.properties");
            conf.setProperty("driverClassName",dbMap.get("driverClassName"));
            conf.setProperty("url",dbMap.get("url"));
            conf.setProperty("username",dbMap.get("username"));
            conf.setProperty("password",dbMap.get("password"));
            conf.save();
            dataSourceConfig.changeDataSource();
        } catch (ConfigurationException e) {
            logger.error("获取数据库配置文件失败:" + e);
            return R.error("保存配置文件时出错" + e);
        }
        return  R.ok();
    }

4.修改Application.java

package com.shulipeng;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;

@ServletComponentScan
@MapperScan("com.shulipeng.dao")
@SpringBootApplication
public class AutocodeApplication {

	private static String[] args;
	private static ConfigurableApplicationContext context;

	public static void main(String[] args) {
		AutocodeApplication.args = args;
		AutocodeApplication.context = SpringApplication.run(AutocodeApplication.class, args);
	}

	public static void restart() {
		context.close();
		AutocodeApplication.context = SpringApplication.run(AutocodeApplication.class, args);

	}
}

 

5.就这样就可以了,只是每次修改数据源就会重启服务。Spring cloud 有一个注解 RefreshScope 好像可以实现不用重启项目就可以动态修改数据源的方式,但是没有接触过,目前这种正好就是我需要的,所以就记录下来了  

  

  

  

转载于:https://www.cnblogs.com/shulipeng/p/8709324.html

你可能感兴趣的:(Springboot 实现前台动态配置数据源 (修改数据源之后自动重启))