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); } }