DynamicDattaSourceAspect.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.util.BasesSource;
  2. import com.dao.DataColumnMapper;
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.model.bo.ToSql;
  6. import org.aspectj.lang.JoinPoint;
  7. import org.aspectj.lang.annotation.After;
  8. import org.aspectj.lang.annotation.Aspect;
  9. import org.aspectj.lang.annotation.Before;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.core.annotation.Order;
  12. import org.springframework.stereotype.Component;
  13. import java.io.IOException;
  14. /**
  15. * @Author caiChaoqi
  16. * @Description 动态数据源通知
  17. * @Date 2018-06-23
  18. */
  19. @Aspect
  20. @Order(-1)//保证在@Transactional之前执行
  21. @Component
  22. public class DynamicDattaSourceAspect {
  23. @Autowired
  24. ObjectMapper objectMapper;
  25. @Autowired
  26. DataColumnMapper dataColumnMapper;
  27. //改变数据源
  28. @Before("@annotation(TargetDataSource)")
  29. public void changeDataSource(JoinPoint joinPoint) {
  30. Object[] arr = joinPoint.getArgs();
  31. String joinStr = null;
  32. ToSql toSql = new ToSql();
  33. // System.out.println("数据源用户名"+baseName);
  34. try {
  35. joinStr = objectMapper.writeValueAsString(arr[1]);
  36. } catch (JsonProcessingException e) {
  37. e.printStackTrace();
  38. }
  39. try {
  40. toSql = objectMapper.readValue(joinStr, ToSql.class);
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. int baseId = toSql.getId();
  45. if (!DynamicDataSourceContextHolder.isContainsDataSource(String.valueOf(baseId))) {
  46. //joinPoint.getSignature() :获取连接点的方法签名对象
  47. System.out.println("数据源 " + String.valueOf(baseId) + " 不存在使用默认的数据源 -> " + joinPoint.getSignature());
  48. } else {
  49. System.out.println("使用数据源:" + String.valueOf(baseId));
  50. DynamicDataSourceContextHolder.setDataSourceType(String.valueOf(baseId));
  51. }
  52. }
  53. @After("@annotation(TargetDataSource)")
  54. public void clearDataSource(JoinPoint joinPoint) {
  55. System.out.println("清除数据源!");
  56. DynamicDataSourceContextHolder.clearDataSourceType();
  57. }
  58. }