springBoot多數據源的yml配置+指定數據源

接上一篇

yml配置

druid: type: com.alibaba.druid.pool.DruidDataSource user: url: jdbc:mysql://localhost:3306/user?characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useUnicode=true&useSSL=true&verifyServerCertificate=false driver-class-name: com.mysql.cj.jdbc.Driver username: root password: initial-size: 5 min-idle: 1 max-active: 100 test-on-borrow: true product: url: jdbc:mysql://localhost:3306/product?characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&useSSL=true&verifyServerCertificate=false driver-class-name: com.mysql.cj.jdbc.Driver username: root password: initial-size: 5 min-idle: 1 max-active: 100 test-on-borrow: true logging: level: com.example.demo.mapper: DEBUG org.springframework.web: DEBUG java.sql: DEBUG org.mybatis.spring: DEBUG

另一種切換數據源的方式

上一章給大家講了SpringBoot的動態切換數據源的配置,如果只是想讀寫分離的話,在第6步使用的時候,可以用如下方法來替換上一章的方式

1.定義一個註解,來標識選擇的數據源

@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface DataSourceSelector { DataSourceKey value() default DataSourceKey.USER; }

2.定義一個切面

@Aspect @Component @Order(20) public class DataSourceSelectorAspect { @Around("@annotation(dataSourceSelector)") public Object proceed(ProceedingJoinPoint pjp, DataSourceSelector dataSourceSelector) throws Throwable { try { DataSourceKey dataSourceKey = dataSourceSelector.value(); DbContextHolder.setDataSourceType(dataSourceKey); Object result = pjp.proceed(); DbContextHolder.clearDataSourceType(); return result; } finally { // restore state DbContextHolder.clearDataSourceType(); } } }

3.使用方式

@Repository public class ProductRepository { @Autowired private ProductMapper productMapper; @DataSourceSelector(value =DataSourceKey.PRODUCT) public Product getProductById(Integer id){ return productMapper.selectByPrimaryKey(id); } }