首页 > 其他分享 >多数据源连接的两种方式

多数据源连接的两种方式

时间:2022-11-05 11:46:02浏览次数:74  
标签:两种 name spring class mysql public 数据源 连接

一、使用AbstractRoutingDataSource注入多种数据源

1、在configuration配置两个数据源

@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.datasource1")
    public DataSource dataSource1(){
        // 底层会自动拿到spring.datasource中的配置, 创建一个DruidDataSource
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.datasource2")
    public DataSource dataSource2(){
        // 底层会自动拿到spring.datasource中的配置, 创建一个DruidDataSource
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager1(DynamicDataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager2(DynamicDataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}

 

2.实现类AbstractRoutingDataSource

@Component
@Primary 
public class DynamicDataSource extends AbstractRoutingDataSource {

    // 当前使用的数据源标识
    public static ThreadLocal<String> name = new ThreadLocal<>();
    @Autowired
    DataSource dataSource1;
    @Autowired
    DataSource dataSource2;

    // 返回当前数据源标识
    @Override
    protected Object determineCurrentLookupKey() {
        return name.get();
    }

    @Override
    public void afterPropertiesSet() {
        // 为targetDataSources初始化所有数据源
        Map<Object, Object> targetDataSources=new HashMap<>();
        targetDataSources.put("d1",dataSource1);
        targetDataSources.put("d2",dataSource2);
        super.setTargetDataSources(targetDataSources);
        // 为defaultTargetDataSource 设置默认的数据源
        super.setDefaultTargetDataSource(dataSource1);
        super.afterPropertiesSet();
    }
}

3、在service业务方法中可以使用对应的数据源

@Service
public class DemoService {

    @Autowired
    DemoMapper demoMapper;


    @Override
    public List<Demo> list() {
        DynamicDataSource.name.set("d1");
        return demoMapper.list();
    }

    @Override
    public void save(Demo demo) {
    // 设置数据源
        DynamicDataSource.name.set("d2");
        demoMapper.save(demo);
    }
}

4.在springboot的application.yml添加数据库的连接信息

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    datasource1:
      url: jdbc:mysql://192.168.189.128:3306/coursedb?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false
      username: root
      password: 123456
      initial-size: 1
      min-idle: 1
      max-active: 20
      test-on-borrow: true
      driver-class-name: com.mysql.cj.jdbc.Driver
    datasource2:
      url: jdbc:mysql://192.168.189.128:3306/coursedb2?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false
      username: root
      password: 123456
      initial-size: 1
      min-idle: 1
      max-active: 20
      test-on-borrow: true
      driver-class-name: com.mysql.cj.jdbc.Driver

由于是springboot项目,在pom.xml使用spring-boot依赖包

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>${version}</version>
    <relativePath/> 
  </parent>

<dependencies>
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
</dependencies>

项目启动类

@SpringBootApplication
@MapperScan("com.demo.mapper")
public class DynamicDatasourceApplication {

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

}

添加一下对应mapper类,bean类

public interface DemoMapper {
    @Select("SELECT * FROM friend")
    List<Friend> list();

    @Insert("INSERT INTO  friend(`name`) VALUES (#{name})")
    void save(Friend friend);
}

 这种方式使用数据源可以稍微改造一下,每次使用数据源都需要 DynamicDataSource.name.set("d1");

通过硬编码的方式设置数据源,可以将其改造为切面的方式

注解类WR 

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface WR {
    String value() default "W";
}

 

@Component
@Aspect
public class DynamicDataSourceAspect{

    // 前置
    @Before("within(com.service.impl.*) && @annotation(wr)")
    public void before(JoinPoint point, WR wr){
        String name = wr.value();
        DynamicDataSource.name.set(name);
    }
}

现在就可以直接在service的方法上直接使用 @WR("R"),不需要再去设置 DynamicDataSource.name.set("W");

二、使用dynamic-datasource注入多种数据源

1、添加依赖包

<dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
      <version>3.5.0</version>
    </dependency>

 

2、配置application.yml的数据源信息

spring:
  datasource:
    dynamic:
      #设置默认的数据源或者数据源组,默认值即为master
      primary: master
      #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      strict: false
      datasource:
        master:
          url: jdbc:mysql://192.168.189.128:3306/coursedb?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false
          username: root
          password: 123456
          initial-size: 1
          min-idle: 1
          max-active: 20
          test-on-borrow: true
          driver-class-name: com.mysql.cj.jdbc.Driver
        slave:
          url: jdbc:mysql://192.168.189.128:3306/coursedb2?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false
          username: root
          password: 123456
          initial-size: 1
          min-idle: 1
          max-active: 20
          test-on-borrow: true
          driver-class-name: com.mysql.cj.jdbc.Driver

3、在service的业务类的方法添加注解 @DS("slave")

@DS("slave")
    @Override
    public List<Friend> list() {
        return friendMapper.list();
    }

 

标签:两种,name,spring,class,mysql,public,数据源,连接
From: https://www.cnblogs.com/yuht-s-learn/p/16859694.html

相关文章