最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用SpringAop動態(tài)獲取mapper執(zhí)行的SQL,并保存SQL到Log表中

 更新時間:2023年03月07日 17:04:46   作者:麥兜仔  
這篇文章主要介紹了使用SpringAop動態(tài)獲取mapper執(zhí)行的SQL,并保存SQL到Log表中問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

1.背景

工作的時候遇到一個這樣的需要,在多機環(huán)境下,使用Mysql作為參數(shù)庫。因為某些原因不能使用Mysql自帶的數(shù)據(jù)同步,所以需要自己實現(xiàn)一個多節(jié)點的Mysql數(shù)據(jù)同步程序。

所以打算人為的設(shè)定主Mysql可讀可寫,備Mysql只能讀。為了保證各個Mysql數(shù)據(jù)的同步,有一個Log表,用于記錄操作主Mysql的SQL語句,從而其他備Mysql只需要通過Log表來進行數(shù)據(jù)同步。

更新:本文章已替換成自定義注解的模式(上版本是基于指定方法名作為切入點)

2.難點

(1)由于項目使用的是Mybatis,不是使用原生的jdbc,所以需要在不影響其他人使用Mybatis開發(fā)的同時,獲取SQL語句并寫入log表

(2)需要保證mapper的操作和log的insert在同一個事務(wù)中

3.實現(xiàn)

3.1ModelSumbit.java

自定義注解,用于Aop切入點

package com.yjy.annotation;
?
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
?
?
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ModelSumbit{
? ?
? ? String value() default "";
}

3.2LogAdvice.java

主要看環(huán)繞通知方法

package com.lyf.aspect;
 
import com.lyf.service.LogService;
import com.lyf.utils.SqlUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
 
 
@Aspect
@Component
public class MyAdvice {
 
    @Autowired
    private LogService logService;
 
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
 
 
    @Pointcut("@annotation(com.yjy.annotation.ModelSumbit)")
    private void pc(){
 
    }
 
    //前置通知
    //指定該方法是前置通知,并指定切入點
    @Before("MyAdvice.pc()")
    public void before(){
//        System.out.println("這是前置通知?。。。?!");
    }
 
    //后置通知
    @AfterReturning("MyAdvice.pc()")
    public void afterReturning(){
//        System.out.println("這是后置通知!(如果出現(xiàn)異常,將不會調(diào)用)?。。?!");
    }
 
    //環(huán)繞通知
    @Around("MyAdvice.pc()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        //1.從redis中獲取主數(shù)據(jù)庫,若獲取不到直接退出,否則判斷當前數(shù)據(jù)源是會否為主,若不為主,則切換到主數(shù)據(jù)源
        //2.調(diào)用目標方法
        Object proceed = pjp.proceed();
        //3.獲取SQL
        String sql = SqlUtils.getMybatisSql(pjp,sqlSessionFactory);
        System.out.println(sql);
        //4.插入日志
        logService.insert(sql);
        //5.通知同步程序
        return proceed;
    }
 
    //異常通知
    @AfterThrowing("MyAdvice.pc()")
    public void afterException(){
//        System.out.println("出事了,拋異常了?。。?!");
    }
 
    //后置通知
    @After("MyAdvice.pc()")
    public void after(){
//        System.out.println("這是后置通知!(無論是否出現(xiàn)異常都會調(diào)用)?。。?!");
    }
}

3.3SqlUtils.java

用于獲取SQL語句

package com.lyf.utils;
 
import com.sun.deploy.util.ArrayUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
 
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.text.DateFormat;
import java.util.*;
 
public class SqlUtils {
 
    /**
     * 獲取aop中的SQL語句
     * @param pjp
     * @param sqlSessionFactory
     * @return
     * @throws IllegalAccessException
     */
    public static String getMybatisSql(ProceedingJoinPoint pjp, SqlSessionFactory sqlSessionFactory) throws IllegalAccessException {
        Map<String,Object> map = new HashMap<>();
        //1.獲取namespace+methdoName
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String namespace = method.getDeclaringClass().getName();
        String methodName = method.getName();
        //2.根據(jù)namespace+methdoName獲取相對應(yīng)的MappedStatement
        Configuration configuration = sqlSessionFactory.getConfiguration();
        MappedStatement mappedStatement = configuration.getMappedStatement(namespace+"."+methodName);
//        //3.獲取方法參數(shù)列表名
//        Parameter[] parameters = method.getParameters();
        //4.形參和實參的映射
        Object[] objects = pjp.getArgs(); //獲取實參
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        for (int i = 0;i<parameterAnnotations.length;i++){
            Object object = objects[i];
            if (parameterAnnotations[i].length == 0){ //說明該參數(shù)沒有注解,此時該參數(shù)可能是實體類,也可能是Map,也可能只是單參數(shù)
                if (object.getClass().getClassLoader() == null && object instanceof Map){
                    map.putAll((Map<? extends String, ?>) object);
                    System.out.println("該對象為Map");
                }else{//形參為自定義實體類
                    map.putAll(objectToMap(object));
                    System.out.println("該對象為用戶自定義的對象");
                }
            }else{//說明該參數(shù)有注解,且必須為@Param
                for (Annotation annotation : parameterAnnotations[i]){
                    if (annotation instanceof Param){
                        map.put(((Param) annotation).value(),object);
                    }
                }
            }
        }
        //5.獲取boundSql
        BoundSql boundSql = mappedStatement.getBoundSql(map);
        return showSql(configuration,boundSql);
    }
 
    /**
     * 解析BoundSql,生成不含占位符的SQL語句
     * @param configuration
     * @param boundSql
     * @return
     */
    private  static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    String[] s =  metaObject.getObjectWrapper().getGetterNames();
                    s.toString();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        return sql;
    }
 
    /**
     * 若為字符串或者日期類型,則在參數(shù)兩邊添加''
     * @param obj
     * @return
     */
    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(new Date()) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
        }
        return value;
    }
 
    /**
     * 獲取利用反射獲取類里面的值和名稱
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    private static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }
}

4.注意事項

  • Mapper接口的增刪改方法上面加上@ModelSumbit注解,才會進入模型數(shù)據(jù)提交AOP
  • Mapper接口方法的形參,可以有如下三種形式

①形參為自定義實體類

@ModelSumbit
void insert(User user);

②形參為Map

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

③形參為單個或多個參數(shù),需要使用@Param注解

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

注意:即便只有一個參數(shù),采用第③方式的時候,仍然需要使用@Param注解

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 關(guān)于springboot中的SPI機制

    關(guān)于springboot中的SPI機制

    這篇文章主要介紹了springboot中的SPI機制,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 實例講解分布式緩存軟件Memcached的Java客戶端使用

    實例講解分布式緩存軟件Memcached的Java客戶端使用

    這篇文章主要介紹了分布式緩存軟件Memcached的Java客戶端使用,Memcached在GitHub上開源,作者用其Windows平臺下的版本進行演示,需要的朋友可以參考下
    2016-01-01
  • 詳解Java中二叉樹的基礎(chǔ)概念(遞歸&迭代)

    詳解Java中二叉樹的基礎(chǔ)概念(遞歸&迭代)

    二叉樹(Binary?tree)是樹形結(jié)構(gòu)的一個重要類型。本文將通過圖片和示例代碼詳細為大家講解一下Java中的二叉樹的基礎(chǔ)概念,需要的可以參考一下
    2022-03-03
  • Java代碼中4種字符串拼接方式分析

    Java代碼中4種字符串拼接方式分析

    本文主要介紹了Java代碼中4種字符串拼接方式分析,主要介紹了“+”號、StringBuilder、StringJoiner、String#join,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • IntelliJ IDEA 關(guān)閉多余項目的操作方法

    IntelliJ IDEA 關(guān)閉多余項目的操作方法

    這篇文章主要介紹了IntelliJ IDEA 關(guān)閉多余項目的操作方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • java使用文件流實現(xiàn)查看下載次數(shù)

    java使用文件流實現(xiàn)查看下載次數(shù)

    這篇文章主要為大家詳細介紹了java使用文件流實現(xiàn)查看下載次數(shù),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Java中的轉(zhuǎn)換流InputStreamReader解讀

    Java中的轉(zhuǎn)換流InputStreamReader解讀

    InputStreamReader是Java.io包中的一個類,用于將字節(jié)輸入流轉(zhuǎn)換為字符輸入流,它繼承自java.io.Reader類,提供了兩種構(gòu)造方法,可以使用默認或指定字符集創(chuàng)建實例,常用方法包括讀取字符、判斷是否準備好讀取數(shù)據(jù)和關(guān)閉流
    2024-09-09
  • Java實現(xiàn)簡單通訊錄管理系統(tǒng)

    Java實現(xiàn)簡單通訊錄管理系統(tǒng)

    這篇文章主要為大家詳細介紹了Java實現(xiàn)簡單通訊錄管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • SpringBoot訪問MongoDB數(shù)據(jù)庫的兩種方式

    SpringBoot訪問MongoDB數(shù)據(jù)庫的兩種方式

    MongoDB是一種非關(guān)系型數(shù)據(jù)庫,通過文檔存儲數(shù)據(jù),適用于大規(guī)模數(shù)據(jù)存儲和高并發(fā)訪問,這篇文章主要介紹了SpringBoot訪問MongoDB數(shù)據(jù)庫的兩種方式,感興趣想要詳細了解可以參考下文
    2023-05-05
  • 線程池中使用spring aop事務(wù)增強

    線程池中使用spring aop事務(wù)增強

    這篇文章主要介紹了線程池中使用spring aop事務(wù)增強,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02

最新評論

淮北市| 会理县| 凌云县| 舞钢市| 库尔勒市| 清水县| 依安县| 天台县| 舞阳县| 禄丰县| 贺州市| 仁化县| 伊宁县| 亚东县| 年辖:市辖区| 玉环县| 南靖县| 当涂县| 西盟| 合阳县| 渝中区| 攀枝花市| 贵港市| 平乡县| 海口市| 宣武区| 南郑县| 西平县| 乌兰察布市| 临安市| 会理县| 科技| 砀山县| 堆龙德庆县| 广东省| 乐都县| 新干县| 梓潼县| 香港| 和政县| 桦南县|