如何使用SpringAop动态获取mapper执行的SQL并保存SQL到Log表中

数据库   发布日期:2023年08月01日   浏览次数:668

本文小编为大家详细介绍“如何使用SpringAop动态获取mapper执行的SQL并保存SQL到Log表中”,内容详细,步骤清晰,细节处理妥当,希望这篇“如何使用SpringAop动态获取mapper执行的SQL并保存SQL到Log表中”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

    1.背景

    工作的时候遇到一个这样的需要,在多机环境下,使用Mysql作为参数库。因为某些原因不能使用Mysql自带的数据同步,所以需要自己实现一个多节点的Mysql数据同步程序。

    所以打算人为的设定主Mysql可读可写,备Mysql只能读。为了保证各个Mysql数据的同步,有一个Log表,用于记录操作主Mysql的SQL语句,从而其他备Mysql只需要通过Log表来进行数据同步。

    2.难点

    (1)由于项目使用的是Mybatis,不是使用原生的jdbc,所以需要在不影响其他人使用Mybatis开发的同时,获取SQL语句并写入log表

    (2)需要保证mapper的操作和log的insert在同一个事务中

    3.实现

    3.1ModelSumbit.java

    自定义注解,用于Aop切入点

    1. package com.yjy.annotation;
    2. import java.lang.annotation.ElementType;
    3. import java.lang.annotation.Retention;
    4. import java.lang.annotation.RetentionPolicy;
    5. import java.lang.annotation.Target;
    6. @Target({ElementType.METHOD})
    7. @Retention(RetentionPolicy.RUNTIME)
    8. public @interface ModelSumbit{
    9. String value() default "";
    10. }

    3.2LogAdvice.java

    主要看环绕通知方法

    1. package com.lyf.aspect;
    2. import com.lyf.service.LogService;
    3. import com.lyf.utils.SqlUtils;
    4. import org.apache.ibatis.session.SqlSessionFactory;
    5. import org.aspectj.lang.ProceedingJoinPoint;
    6. import org.aspectj.lang.annotation.*;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Component;
    9. @Aspect
    10. @Component
    11. public class MyAdvice {
    12. @Autowired
    13. private LogService logService;
    14. @Autowired
    15. private SqlSessionFactory sqlSessionFactory;
    16. @Pointcut("@annotation(com.yjy.annotation.ModelSumbit)")
    17. private void pc(){
    18. }
    19. //前置通知
    20. //指定该方法是前置通知,并指定切入点
    21. @Before("MyAdvice.pc()")
    22. public void before(){
    23. // System.out.println("这是前置通知!!!!!");
    24. }
    25. //后置通知
    26. @AfterReturning("MyAdvice.pc()")
    27. public void afterReturning(){
    28. // System.out.println("这是后置通知!(如果出现异常,将不会调用)!!!!");
    29. }
    30. //环绕通知
    31. @Around("MyAdvice.pc()")
    32. public Object around(ProceedingJoinPoint pjp) throws Throwable{
    33. //1.从redis中获取主数据库,若获取不到直接退出,否则判断当前数据源是会否为主,若不为主,则切换到主数据源
    34. //2.调用目标方法
    35. Object proceed = pjp.proceed();
    36. //3.获取SQL
    37. String sql = SqlUtils.getMybatisSql(pjp,sqlSessionFactory);
    38. System.out.println(sql);
    39. //4.插入日志
    40. logService.insert(sql);
    41. //5.通知同步程序
    42. return proceed;
    43. }
    44. //异常通知
    45. @AfterThrowing("MyAdvice.pc()")
    46. public void afterException(){
    47. // System.out.println("出事了,抛异常了!!!!");
    48. }
    49. //后置通知
    50. @After("MyAdvice.pc()")
    51. public void after(){
    52. // System.out.println("这是后置通知!(无论是否出现异常都会调用)!!!!");
    53. }
    54. }

    3.3SqlUtils.java

    用于获取SQL语句

    1. package com.lyf.utils;
    2. import com.sun.deploy.util.ArrayUtil;
    3. import org.apache.ibatis.annotations.Param;
    4. import org.apache.ibatis.mapping.BoundSql;
    5. import org.apache.ibatis.mapping.MappedStatement;
    6. import org.apache.ibatis.mapping.ParameterMapping;
    7. import org.apache.ibatis.reflection.MetaObject;
    8. import org.apache.ibatis.session.Configuration;
    9. import org.apache.ibatis.session.SqlSessionFactory;
    10. import org.apache.ibatis.type.TypeHandlerRegistry;
    11. import org.aspectj.lang.ProceedingJoinPoint;
    12. import org.aspectj.lang.reflect.MethodSignature;
    13. import java.lang.annotation.Annotation;
    14. import java.lang.reflect.Field;
    15. import java.lang.reflect.Method;
    16. import java.lang.reflect.Parameter;
    17. import java.text.DateFormat;
    18. import java.util.*;
    19. public class SqlUtils {
    20. /**
    21. * 获取aop中的SQL语句
    22. * @param pjp
    23. * @param sqlSessionFactory
    24. * @return
    25. * @throws IllegalAccessException
    26. */
    27. public static String getMybatisSql(ProceedingJoinPoint pjp, SqlSessionFactory sqlSessionFactory) throws IllegalAccessException {
    28. Map<String,Object> map = new HashMap<>();
    29. //1.获取namespace+methdoName
    30. MethodSignature signature = (MethodSignature) pjp.getSignature();
    31. Method method = signature.getMethod();
    32. String namespace = method.getDeclaringClass().getName();
    33. String methodName = method.getName();
    34. //2.根据namespace+methdoName获取相对应的MappedStatement
    35. Configuration configuration = sqlSessionFactory.getConfiguration();
    36. MappedStatement mappedStatement = configuration.getMappedStatement(namespace+"."+methodName);
    37. // //3.获取方法参数列表名
    38. // Parameter[] parameters = method.getParameters();
    39. //4.形参和实参的映射
    40. Object[] objects = pjp.getArgs(); //获取实参
    41. Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    42. for (int i = 0;i<parameterAnnotations.length;i++){
    43. Object object = objects[i];
    44. if (parameterAnnotations[i].length == 0){ //说明该参数没有注解,此时该参数可能是实体类,也可能是Map,也可能只是单参数
    45. if (object.getClass().getClassLoader() == null && object instanceof Map){
    46. map.putAll((Map<? extends String, ?>) object);
    47. System.out.println("该对象为Map");
    48. }else{//形参为自定义实体类
    49. map.putAll(objectToMap(object));
    50. System.out.println("该对象为用户自定义的对象");
    51. }
    52. }else{//说明该参数有注解,且必须为@Param
    53. for (Annotation annotation : parameterAnnotations[i]){
    54. if (annotation instanceof Param){
    55. map.put(((Param) annotation).value(),object);
    56. }
    57. }
    58. }
    59. }
    60. //5.获取boundSql
    61. BoundSql boundSql = mappedStatement.getBoundSql(map);
    62. return showSql(configuration,boundSql);
    63. }
    64. /**
    65. * 解析BoundSql,生成不含占位符的SQL语句
    66. * @param configuration
    67. * @param boundSql
    68. * @return
    69. */
    70. private static String showSql(Configuration configuration, BoundSql boundSql) {
    71. Object parameterObject = boundSql.getParameterObject();
    72. List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    73. String sql = boundSql.getSql().replaceAll("[s]+", " ");
    74. if (parameterMappings.size() > 0 && parameterObject != null) {
    75. TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
    76. if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
    77. sql = sql.replaceFirst("?", getParameterValue(parameterObject));
    78. } else {
    79. MetaObject metaObject = configuration.newMetaObject(parameterObject);
    80. for (ParameterMapping parameterMapping : parameterMappings) {
    81. String propertyName = parameterMapping.getProperty();
    82. String[] s = metaObject.getObjectWrapper().getGetterNames();
    83. s.toString();
    84. if (metaObject.hasGetter(propertyName)) {
    85. Object obj = metaObject.getValue(propertyName);
    86. sql = sql.replaceFirst("?", getParameterValue(obj));
    87. } else if (boundSql.hasAdditionalParameter(propertyName)) {
    88. Object obj = boundSql.getAdditionalParameter(propertyName);
    89. sql = sql.replaceFirst("?", getParameterValue(obj));
    90. }
    91. }
    92. }
    93. }
    94. return sql;
    95. }
    96. /**
    97. * 若为字符串或者日期类型,则在参数两边添加''
    98. * @param obj
    99. * @return
    100. */
    101. private static String getParameterValue(Object obj) {
    102. String value = null;
    103. if (obj instanceof String) {
    104. value = "'" + obj.toString() + "'";
    105. } else if (obj instanceof Date) {
    106. DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
    107. value = "'" + formatter.format(new Date()) + "'";
    108. } else {
    109. if (obj != null) {
    110. value = obj.toString();
    111. } else {
    112. value = "";
    113. }
    114. }
    115. return value;
    116. }
    117. /**
    118. * 获取利用反射获取类里面的值和名称
    119. *
    120. * @param obj
    121. * @return
    122. * @throws IllegalAccessException
    123. */
    124. private static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
    125. Map<String, Object> map = new HashMap<>();
    126. Class<?> clazz = obj.getClass();
    127. System.out.println(clazz);
    128. for (Field field : clazz.getDeclaredFields()) {
    129. field.setAccessible(true);
    130. String fieldName = field.getName();
    131. Object value = field.get(obj);
    132. map.put(fieldName, value);
    133. }
    134. return map;
    135. }
    136. }

    4.注意事项

    • Mapper接口的增删改方法上面加上@ModelSumbit注解,才会进入模型数据提交AOP

    • Mapper接口方法的形参,可以有如下三种形式

    ①形参为自定义实体类

    1. @ModelSumbit
    2. void insert(User user);

    ②形参为Map

    1. @ModelSumbit
    2. void insert(Map<String,Object> map);

    ③形参为单个或多个参数,需要使用@Param注解

    1. @ModelSumbit
    2. void insert(@Param("userName") String userName, @Param("age")Integer age);

    注意:即便只有一个参数,采用第③方式的时候,仍然需要使用@Param注解

    以上就是如何使用SpringAop动态获取mapper执行的SQL并保存SQL到Log表中的详细内容,更多关于如何使用SpringAop动态获取mapper执行的SQL并保存SQL到Log表中的资料请关注九品源码其它相关文章!