DataSourceAspect.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.fjhx.common.aspect;
  2. import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
  3. import com.fjhx.common.constant.SourceConstant;
  4. import org.aspectj.lang.ProceedingJoinPoint;
  5. import org.aspectj.lang.annotation.Around;
  6. import org.aspectj.lang.annotation.Aspect;
  7. import org.aspectj.lang.annotation.Pointcut;
  8. import org.springframework.core.Ordered;
  9. import org.springframework.core.annotation.Order;
  10. import org.springframework.stereotype.Component;
  11. import java.lang.reflect.Field;
  12. import java.util.HashSet;
  13. import java.util.Set;
  14. @Aspect
  15. @Component
  16. @Order(Ordered.HIGHEST_PRECEDENCE)
  17. public class DataSourceAspect {
  18. private static final Set<String> dataSourceSet = new HashSet<>();
  19. static {
  20. Class<SourceConstant> sourceConstantClass = SourceConstant.class;
  21. Field[] declaredFields = sourceConstantClass.getDeclaredFields();
  22. for (Field declaredField : declaredFields) {
  23. dataSourceSet.add(declaredField.getName().toLowerCase());
  24. }
  25. }
  26. @Pointcut("execution (* com.fjhx.*.service.*.*.*(..))")
  27. public void pointcut() {
  28. }
  29. @Around(value = "pointcut()")
  30. public Object before(ProceedingJoinPoint point) throws Throwable {
  31. // Object target = point.getTarget();
  32. // String name = target.getClass().getName();
  33. // String moduleName = name.split("\\.")[2];
  34. //
  35. // String peek = DynamicDataSourceContextHolder.peek();
  36. // if (Objects.equals(peek, moduleName)) {
  37. // return point.proceed();
  38. // }
  39. //
  40. // if (dataSourceSet.contains(moduleName)) {
  41. // try {
  42. // DynamicDataSourceContextHolder.push(moduleName);
  43. // return point.proceed();
  44. // } finally {
  45. // DynamicDataSourceContextHolder.poll();
  46. // }
  47. // } else {
  48. // return point.proceed();
  49. // }
  50. try {
  51. DynamicDataSourceContextHolder.push(SourceConstant.BASE);
  52. return point.proceed();
  53. } finally {
  54. DynamicDataSourceContextHolder.poll();
  55. }
  56. }
  57. }