Bladeren bron

新增动态数据源切换AOP

zhouchenglin 7 jaren geleden
bovenliggende
commit
e0b8cd43e5

+ 17 - 0
src/main/java/net/chenlin/dp/common/annotation/DataSource.java

@@ -0,0 +1,17 @@
+package net.chenlin.dp.common.annotation;
+
+import java.lang.annotation.*;
+
+/**
+ * 数据源注解
+ * @author ZhouChenglin
+ * @date 2018/2/7
+ */
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface DataSource {
+
+    String value() default "";
+
+}

+ 58 - 0
src/main/java/net/chenlin/dp/common/aspect/DataSourceAspect.java

@@ -0,0 +1,58 @@
+package net.chenlin.dp.common.aspect;
+
+import net.chenlin.dp.common.annotation.DataSource;
+import net.chenlin.dp.common.support.orm.db.DataSourceEnum;
+import net.chenlin.dp.common.support.orm.db.DynamicDataSource;
+import org.apache.commons.lang.StringUtils;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Method;
+
+/**
+ * 数据源切面处理
+ * @author ZhouChenglin
+ * @date 2018/2/7
+ */
+@Aspect
+@Component
+public class DataSourceAspect {
+
+    private static Logger LOG = LoggerFactory.getLogger(DataSourceAspect.class);
+
+    @Pointcut("@annotation(net.chenlin.dp.common.annotation.DataSource)")
+    public void pointCut() {
+
+    }
+
+    @Around("pointCut()")
+    public Object doAround(ProceedingJoinPoint point) throws Throwable {
+        MethodSignature signature = (MethodSignature) point.getSignature();
+        Method method = signature.getMethod();
+        DataSource ds = method.getAnnotation(DataSource.class);
+
+        String dataSource = ds.value();
+        if (StringUtils.isBlank(dataSource)) {
+            DynamicDataSource.setDataSource(DataSourceEnum.MASTER.getName());
+            LOG.debug("set datasource is null, use datasource : {}", dataSource);
+        } else {
+            DynamicDataSource.setDataSource(dataSource);
+            LOG.debug("use datasource : {}", dataSource);
+        }
+
+        try {
+            return point.proceed();
+        } finally {
+            DynamicDataSource.clearDataSource();
+            LOG.debug("clear datasource...");
+        }
+
+    }
+
+}