1. 修改项目配置yml
2. 修改项目文件
数据源切换注解
@Target({/*ElementType.TYPE,*/ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
DataSourceEnum value() default DataSourceEnum.DB1;
}
切面拦截
@Component
@Slf4j
@Aspect
@Order(-1)
public class DataSourceAspect {
@Pointcut("@within(com.service.muldb2.config.db.DataSource) || @annotation(com.service.muldb2.config.db.DataSource)")
public void pointCut() {
}
@Before("pointCut() && @annotation(dataSource)")
public void doBefore(DataSource dataSource) {
String ds = dataSource.value().getValue();
if (StringUtils.isBlank(ds)) {
ds = DataSourceEnum.DB1.getValue();
}
MultipleDataSource.setDataSource(ds);
}
@After("pointCut()")
public void doAfter() {
MultipleDataSource.clear();
}
}
数据源枚举
@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public enum DataSourceEnum {
DB1("db1"),
DB2("db2");
private String value;
}
数据源路由
public class MultipleDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>();
public static String getDataSource() {
return contextHolder.get();
}
public static void setDataSource(String db) {
contextHolder.set(db);
}
public static void clear() {
contextHolder.remove();
}
@Override
protected Object determineCurrentLookupKey() {
return this.getDataSource();
}
}
设置ORM
使用注解切换数据源