在配置数据源时候,已经把主库和从库的数据源配置到DynamicDataSource里了
利用AbstractRoutingDataSource实现动态切换数据源,可以通过注解或者根据方法名前缀切换要使用的数据源
这里主库和从库要做主从同步,这样就实现了数据库的读写分离
AOP的执行顺序 ,order值越小,越先被执行
/**
* order 的值越小,说明越先被执行
*
*/
@Aspect
@Component
@Order()
@Slf4j
public class DataSourceAspect{ /**
* 注解方式
* @param joinPoint
* @param dataSource
*/
@Before(value = "@annotation(dataSource)")
public void dataSourcePoint(JoinPoint joinPoint, DataSource dataSource) {
DynamicDataSourceHolder.putDataSource(dataSource.value());
log.info("通过注解 dataSource 切换到:{}",dataSource.value());
} }
@Aspect
@Component
@Order(-)
@Slf4j
public class DataSourcePartAspect {
/**
* mapper 查询操作默认使用从库
*/
@Before("execution(* com..service..*.select*(..)) || execution(* com..service..*.get*(..))|| execution(* com..service..*.query*(..))")
public void setReadDataSourceType() {
DynamicDataSourceHolder.putDataSource(DataSourceType.SLAVE);
log.info("dataSource 切换到:{}",DataSourceType.SLAVE.getName());
} /**
* mapper 修改删除操作默认使用主库库
*/
@Before("execution(* com..service..*.insert*(..)) || execution(* com..service..*.update*(..)) || execution(* com..service..*.delete*(..))")
public void setWriteDataSourceType() {
DynamicDataSourceHolder.putDataSource(DataSourceType.MASTER);
log.info("dataSource 切换到:{}",DataSourceType.MASTER.getName());
} }
项目结构:
github下载地址: