Spring Boot配置多数据源并实现Druid自动切换

Spring Boot配置多数据源

配置yml文件

这里并没有对spring.datasource配置数据源,因为增加新数据源后,系统会覆盖由spring.datasource自动配置的内容。
这里自定义了两个数据源spring.datasource.cmmi和spring.datasource.zentao

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    base:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      initialize: true #指定初始化数据源,是否用data.sql来初始化,默认: true
      name: cmmi
      url: jdbc:mysql://127.0.0.1:3306/cmmi?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
      username: root
      password: root
    zentao:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      initialize: true
      name: zentaopro
      url: jdbc:mysql://127.0.0.1:3306/zentaopro?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
      username: root
      password: root

主数据源配置

注意,配置类需要对DataSource、DataSourceTransactionManager、SqlSessionFactory 、SqlSessionTemplate四个数据项进行配置;DataSource类型需要引入javax.sql.DataSource;当系统中有多个数据源时,必须有一个数据源为主数据源,使用@Primary修饰。
@MapperScan对指定dao包建立映射,确保在多个数据源下,自动选择合适的数据源,而在service层里不需要做特殊说明。

@Configuration
@MapperScan(basePackages = "cmmi.dao.base", sqlSessionTemplateRef = "baseSqlSessionTemplate")
public class BaseDataSourceConfig {
    @Bean(name = "baseDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.base")
    @Primary
    public DataSource setDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "baseTransactionManager")
    @Primary
    public DataSourceTransactionManager setTransactionManager(@Qualifier("baseDataSource") DataSource dataSource) {
        return new DruidDataSource();
    }

    @Bean(name = "baseSqlSessionFactory")
    @Primary
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/base/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "baseSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

从数据源配置

@Configuration
@MapperScan(basePackages = "cmmi.dao.zentao", sqlSessionTemplateRef = "zentaoSqlSessionTemplate")
public class ZentaoDataSourceConfig {
    @Bean(name = "zentaoDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.zentao")
    public DataSource setDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "zentaoTransactionManager")
    public DataSourceTransactionManager setTransactionManager(@Qualifier("zentaoDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "zentaoSqlSessionFactory")
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("zentaoDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/zentao/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "zentaoSqlSessionTemplate")
    public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("zentaoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

使用dao

这里只需要正常使用dao就可以了,spring会根据数据源配置的映射自动选择相应数据源,而不需要在service做特殊说明。

@Service
public class TestService {
    private final ZtUserMapper ztUserMapper;
    private final LevelDic levelDic;

    @Autowired
    public TestService(ZtUserMapper ztUserMapper, LevelDic levelDic) {
        this.ztUserMapper = ztUserMapper;
        this.levelDic = levelDic;
    }

    public void test() {
        ztUserMapper.selectByPrimaryKey(1);
        levelDic.setDicId(new Integer(1).byteValue());
    }
}

日志

o.a.c.c.C.[Tomcat].[localhost].[/cmmi] : Initializing Spring FrameworkServlet ‘dispatcherServlet’
o.s.web.servlet.DispatcherServlet : FrameworkServlet ‘dispatcherServlet’: initialization started
o.s.web.servlet.DispatcherServlet : FrameworkServlet ‘dispatcherServlet’: initialization completed in 23 ms
com.alibaba.druid.pool.DruidDataSource : {dataSource-1,cmmi} inited
com.alibaba.druid.pool.DruidDataSource : {dataSource-2,zentaopro} inited

  • 10
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
Spring Boot中,配置Druid多数据源有以下几个步骤: 1. 引入依赖:在`pom.xml`文件中,引入Druid和jdbc依赖。 ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.4</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> ``` 2. 配置数据源信息:在`application.properties`或`application.yml`配置文件中,配置Druid数据源相关信息,包括数据库URL、用户名、密码等。 ```properties # 主数据源 spring.datasource.url=jdbc:mysql://localhost:3306/main_db?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 第二个数据源 spring.second-datasource.url=jdbc:mysql://localhost:3306/second_db?useUnicode=true&characterEncoding=UTF-8 spring.second-datasource.username=root spring.second-datasource.password=root spring.second-datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 配置多数据源:在`@Configuration`类中,配置多个Druid数据源,并将其注入到`DataSource`对象中。 ```java @Configuration public class DataSourceConfig { @Bean(name = "mainDataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource mainDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "secondDataSource") @ConfigurationProperties(prefix = "spring.second-datasource") public DataSource secondDataSource() { return DruidDataSourceBuilder.create().build(); } } ``` 4. 配置事务管理器:在`@Configuration`类中,配置多数据源的事务管理器,用于管理多个数据源的事务。 ```java @Configuration public class TransactionManagerConfig { @Autowired @Qualifier("mainDataSource") private DataSource mainDataSource; @Autowired @Qualifier("secondDataSource") private DataSource secondDataSource; @Bean public PlatformTransactionManager mainTransactionManager() { return new DataSourceTransactionManager(mainDataSource); } @Bean public PlatformTransactionManager secondTransactionManager() { return new DataSourceTransactionManager(secondDataSource); } } ``` 5. 使用多数据源:在需要使用的地方,使用注解来指定使用哪个数据源。 ```java @Service public class UserService { @Autowired @Qualifier("mainDataSource") private JdbcTemplate mainJdbcTemplate; @Autowired @Qualifier("secondDataSource") private JdbcTemplate secondJdbcTemplate; public List<User> getAllUsersFromMainDataSource() { return mainJdbcTemplate.query("SELECT * FROM users", new BeanPropertyRowMapper(User.class)); } public List<User> getAllUsersFromSecondDataSource() { return secondJdbcTemplate.query("SELECT * FROM users", new BeanPropertyRowMapper(User.class)); } } ``` 通过以上步骤,我们就成功配置Druid多数据源,并且可以在代码中灵活地使用不同的数据源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值