## datasource master # spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/master?characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123456 ## datasource slave # spring.datasource-slave.type=com.alibaba.druid.pool.DruidDataSource spring.datasource-slave.driver-class-name=com.mysql.jdbc.Driver spring.datasource-slave.url=jdbc:mysql://localhost:3306/slave?characterEncoding=UTF-8&serverTimezone=UTC spring.datasource-slave.username=root spring.datasource-slave.password=123456
public interface Datasources { String MASTER_DB = "masterDB"; String SLAVE_DB = "slaveDB"; }
@Configuration public class DataSourceConfig { //destroy-method="close"的做用是當數據庫鏈接不使用的時候,就把該鏈接從新放到數據池中,方便下次使用調用. @Bean(destroyMethod = "close", name = Datasources.MASTER_DB) @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return DataSourceBuilder.create().type(DruidDataSource.class).build(); } @Bean(destroyMethod = "close", name = Datasources.SLAVE_DB) @ConfigurationProperties(prefix = "spring.datasource-slave") public DataSource dataSourceSlave() { return DataSourceBuilder.create().type(DruidDataSource.class).build(); } }
@Configuration @MapperScan(basePackages = {"com.example.dao"}) public class MybatisConfig { @Autowired @Qualifier(Datasources.MASTER_DB) private DataSource masterDB; @Autowired @Qualifier(Datasources.SLAVE_DB) private DataSource slaveDB; /** * 動態數據源 */ @Bean(name = "dynamicDataSource") public DataSource dynamicDataSource() { DynamicDataSource dynamicDataSource = new DynamicDataSource(); // 默認數據源 dynamicDataSource.setDefaultTargetDataSource(masterDB); // 配置多數據源 Map<Object, Object> dsMap = new HashMap<>(); dsMap.put(Datasources.MASTER_DB, masterDB); dsMap.put(Datasources.SLAVE_DB, slaveDB); dynamicDataSource.setTargetDataSources(dsMap); return dynamicDataSource; } @Bean @ConfigurationProperties(prefix = "mybatis") public SqlSessionFactoryBean sqlSessionFactoryBean() { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // 配置數據源,此處配置爲關鍵配置,若是沒有將 dynamicDataSource 做爲數據源則不能實現切換 sqlSessionFactoryBean.setDataSource(dynamicDataSource()); return sqlSessionFactoryBean; } }
public class DataSourceContextHolder { /** * 默認數據源 */ public static final String DEFAULT_DATASOURCE = Datasources.MASTER_DB; private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); // 設置數據源名 public static void setDB(String dbType) { System.out.println("切換到{}數據源:" + dbType); contextHolder.set(dbType); } // 獲取數據源名 public static String getDB() { return (contextHolder.get()); } // 清除數據源名 public static void clearDB() { contextHolder.remove(); } }
@Aspect @Component public class DynamicDataSourceAspect { @Before("@annotation(com.example.util.RoutingDataSource)") public void beforeSwitchDS(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); String dataSource = DataSourceContextHolder.DEFAULT_DATASOURCE; if (method.isAnnotationPresent(RoutingDataSource.class)) { RoutingDataSource routingDataSource = method.getDeclaredAnnotation(RoutingDataSource.class); dataSource = routingDataSource.value(); } DataSourceContextHolder.setDB(dataSource); } @After("@annotation(com.example.util.RoutingDataSource)") public void afterSwitchDS(JoinPoint point) { DataSourceContextHolder.clearDB(); } }
public class DynamicDataSource extends AbstractRoutingDataSource{ @Override protected Object determineCurrentLookupKey() { System.out.println("數據源爲{}:" + DataSourceContextHolder.getDB()); return DataSourceContextHolder.getDB(); } }
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class CutDataBaseApplication { public static void main(String[] args) { SpringApplication.run(CutDataBaseApplication.class, args); } }
/** * @author aYong * @version 1.0 * @date 2019/7/24 */ @RestController @RequestMapping("/route") public class SysUserController { @Autowired private SysUserService sysUserService; @GetMapping("/test1") public SysUser test1(long id) { return sysUserService.test1(id); } @GetMapping("/test2") public Integer test2(long id, String name) { return sysUserService.test2(id, name); } }
git源碼傳送門java