|
|
@@ -2,12 +2,16 @@ package com.uas.erp.database.datasource;
|
|
|
|
|
|
import org.aspectj.lang.JoinPoint;
|
|
|
import org.aspectj.lang.annotation.After;
|
|
|
+import org.aspectj.lang.annotation.AfterThrowing;
|
|
|
import org.aspectj.lang.annotation.Aspect;
|
|
|
import org.aspectj.lang.annotation.Before;
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.core.annotation.Order;
|
|
|
import org.springframework.stereotype.Component;
|
|
|
|
|
|
+import java.sql.SQLException;
|
|
|
+import java.sql.SQLRecoverableException;
|
|
|
+
|
|
|
/**
|
|
|
* Created by Pro1 on 2017/7/27.
|
|
|
*/
|
|
|
@@ -21,23 +25,51 @@ public class DynamicDataSourceAspect {
|
|
|
|
|
|
@Before("@annotation(dataSource)")
|
|
|
public void changeDataSource(JoinPoint point, TargetDataSource dataSource) throws Throwable {
|
|
|
+ Connectable connectable = getConnectableByPoint(point);
|
|
|
+ if (null != connectable) {
|
|
|
+ // 防止数据源未创建
|
|
|
+ dataSourceRegister.createDataSource(connectable);
|
|
|
+ DynamicDataSourceContextHolder.set(connectable);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @After("@annotation(dataSource)")
|
|
|
+ public void restoreDataSource(JoinPoint point, TargetDataSource dataSource) {
|
|
|
+ DynamicDataSourceContextHolder.clear();
|
|
|
+ }
|
|
|
+
|
|
|
+ @AfterThrowing(value = "@annotation(dataSource)", throwing = "e")
|
|
|
+ public void catchThrowing(JoinPoint point, TargetDataSource dataSource, Throwable e) {
|
|
|
+ if (e.getCause() instanceof SQLException) {
|
|
|
+ Connectable connectable = getConnectableByPoint(point);
|
|
|
+ if (null != connectable) {
|
|
|
+ SQLException ex = (SQLException)e.getCause();
|
|
|
+ switch (ex.getErrorCode()){
|
|
|
+ case 1017:
|
|
|
+ // ORA-01017: invalid username/password
|
|
|
+ dataSourceRegister.unregister(connectable);
|
|
|
+ break;
|
|
|
+ case 17002:
|
|
|
+ // The Network Adapter could not establish the connection
|
|
|
+ dataSourceRegister.unregister(connectable);
|
|
|
+ break;
|
|
|
+ default:
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Connectable getConnectableByPoint(JoinPoint point) {
|
|
|
if (null != point.getArgs()) {
|
|
|
for (Object arg: point.getArgs()) {
|
|
|
// 按参数类型为Connectable的进行数据源切换
|
|
|
if (null != arg && arg instanceof Connectable) {
|
|
|
- Connectable connectable = (Connectable) arg;
|
|
|
- // 防止数据源未创建
|
|
|
- dataSourceRegister.createDataSource(connectable);
|
|
|
- DynamicDataSourceContextHolder.set(connectable);
|
|
|
- break;
|
|
|
+ return (Connectable) arg;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
- }
|
|
|
-
|
|
|
- @After("@annotation(dataSource)")
|
|
|
- public void restoreDataSource(JoinPoint point, TargetDataSource dataSource) {
|
|
|
- DynamicDataSourceContextHolder.clear();
|
|
|
+ return null;
|
|
|
}
|
|
|
|
|
|
}
|