Osheep

时光不回头,当下最重要。

Spring Boot多数据源配置及简单使用

《Spring Boot多数据源配置及简单使用》

Spring Boot

背景

  • 我需要操作多个数据库,一个是业务数据库,一个是SuperDiamond
  • 我本来想用MyBatis去动态切换数据源的,后来发现在MyBatis层做真是太麻烦了(其实是我不会。。。),还不如Spring Boot配置两个数据源。
  • 基本sql操作可以,但是还有一个问题是,如何和MyBatis集成并且做动态的切换,这还需要再研究一下。

废话少说,直接贴源码吧!

application.yml

spring:
    datasource:
      readSize: 1
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/defaultdb
      username: test
      password: test
superdiamond:
    datasource:
      readSize: 1
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/superdiamond
      username: admin
      password: admin

DataSourceConfig.java

@Configuration
public class DataSourceConfig {
    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    @Bean(name = "dataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDataSource() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    @Bean(name = "superDiamondDataSource")
    @ConfigurationProperties(prefix = "superdiamond.datasource")
    public DataSource getSuperDiamondDataSource() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
}

MyTestService.java

@Service
public class MyTestService {
    @Autowired DataSourceConfig dataSourceConfig;
    public void updateSuperDiamondValue(String key, String value) {
        DataSource dataSource = dataSourceConfig.getSuperDiamondDataSource();
        try {
            Connection conn = dataSource.getConnection();
            PreparedStatement stmt = null;
            stmt = conn.prepareStatement("update conf_project_config set CONFIG_VALUE ='" + value + "' WHERE CONFIG_KEY ='" + key + "';");
            stmt.execute();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

http://blog.didispace.com/springbootmultidatasource/
http://www.jianshu.com/p/dd33708eefc9

点赞