10月20日,北京【人工智能】源创会火热报名中,点击报名收获 AI 训练指南
Watch Star Fork

如果没有你 / dynamic-datasource-spring-boot-starterJavaApache-2.0

Sign up for free
Explore and code with more than 2 million developers,Free private repositories !:)
Sign up
springBoot 多数据源 动态数据源 主从分离 快速启动器
Loading...
README.md 5.04 KB

dynamic-datasource-spring-boot-starter

Build Status Maven central License

Github | Gitee

English introduction | 中文说明

Introduction

dynamic-datasource-spring-boot-starter based on springBoot2.0.

It can be used for Separation of reading and writing.

The master database to INSERT UPDATE DELETE .

The slave database to SELECT .

If you project is complex,I will propose you use sharding-jdbc .

Demo

dynamic-datasource-example a simple dynamic project that u can direct run。

How to use

  1. Import dynamic-datasource-spring-boot-starter。
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
  <version>${version}</version>
</dependency>
  1. Config your master-slave info in application.yml。

spring.datasource.dynamic.master (config the unique master database)

spring.datasource.dynamic.slave (config every slave database)

spring:
  datasource:
    dynamic:
      master:
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://47.100.20.186:3307/dynamic?characterEncoding=utf8&useSSL=false
      slave:
        one:
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://47.100.20.186:3308/dynamic?characterEncoding=utf8&useSSL=false
        two:
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://47.100.20.186:3309/dynamic?characterEncoding=utf8&useSSL=false
  1. Use annotation @DS to switch database.

@DS can be annotation on serviceImpl method or mybatis mapper method.

annotation result
without @DS master
@DS("one") If exist a database named 'one' then switch to one,otherwise to master
@DS depensOn DynamicDataSourceStrategy to determine a slave database,the default strategy is LoadBalance.
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @DS("one")
  public List<Map<String, Object>> selectAll() {
    return  jdbcTemplate.queryForList("select * from user");
  }
  
  @Override
  @DS
  public List<Map<String, Object>> selectByCondition() {
    return  jdbcTemplate.queryForList("select * from user where age >10");
  }

}

In mybatis environment it can also annotation on mapper method.

public interface UserMapper {

  @Insert("INSERT INTO user (name,age) values (#{name},#{age})")
  boolean addUser(@Param("name") String name, @Param("age") Integer age);

  @Update("UPDATE user set name=#{name}, age=#{age} where id =#{id}")
  boolean updateUser(@Param("id") Integer id, @Param("name") String name, @Param("age") Integer age);

  @Delete("DELETE from user where id =#{id}")
  boolean deleteUser(@Param("id") Integer id);

  @Select("SELECT * FROM user")
  @DS
  List<User> selectAll();

}

Custom config

  1. Config DynamicDataSourceProvider .

The default DynamicDataSourceProvider is YmlDynamicDataSourceProvider,It read database info from application.yaml or application.properties .

public interface DynamicDataSourceProvider {

  /**
   * load master
   *
   * @return masterDataSource
   */
  DataSource loadMasterDataSource();

  /**
   * load slaves
   *
   * @return slaveDataSource
   */
  Map<String, DataSource> loadSlaveDataSource();

}
  1. Config DynamicDataSourceStrategy.

The default DynamicDataSourceStrategy is LoadBalanceDynamicDataSourceStrategy .

The starter alse provide RandomDynamicDataSourceStrategy.

public interface DynamicDataSourceStrategy {

  /**
   * determine a slaveId
   *
   * @param slaveDataSourceLookupKeys slaveKeys
   * @return slaveId
   */
  String determineSlaveDataSource(String[] slaveDataSourceLookupKeys);

}

Demo to use RandomDynamicDataSourceStrategy instead of LoadBalanceDynamicDataSourceStrategy .

@Configuration
public class DynamicConfiguration {
 
  @Bean
  public DynamicDataSourceStrategy dynamicDataSourceStrategy() {
    return new RandomDynamicDataSourceStrategy();
  }

}

Comments ( 0 )

You need to Sign in for post a comment

Help Search