这里
插件内容如下
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.toolkit.PluginUtils;
import com.jinhui.community.common.thread.BussinessLogThrad;
import com.jinhui.community.common.thread.ThreadPoolExecutorTool;
import com.jinhui.community.common.util.HttpKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* SQL 执行拦截器
*
* @author zhangsy
* @date 2020-10-20 21:26
*/
@Slf4j
@Component
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class SqlRecordInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
String id = mappedStatement.getId();
SqlCommandType type = mappedStatement.getSqlCommandType();
BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
String originalSql = boundSql.getSql();
Object parameterObject = boundSql.getParameterObject();
//查找参数中包含DataScope类型的参数
String ip = HttpKit.geRequestIp();
if(null == ip){
return invocation.proceed();
}
Map param = null;
if(parameterObject instanceof MapperMethod.ParamMap){
param = (MapperMethod.ParamMap)parameterObject;
}
Long userId = HttpKit.getUserId();
Map reutnmap = new HashMap<>();
reutnmap.put("id", id );
reutnmap.put("type", type );
reutnmap.put("sql", originalSql );
reutnmap.put("param", param == null ? null: JSONUtil.toJsonStr(param));
reutnmap.put("ip", ip );
reutnmap.put("userId", HttpKit.getUserId());
Integer typeCode = 0;
/**
* 日志类型。1:添加2:编辑 3:删除 4:导入5:导出6:用户角色变更7:角色权限变更
*/
if (SqlCommandType.SELECT.equals(type)) {
typeCode = 8;
}else if (SqlCommandType.DELETE.equals(type)) {
typeCode = 3;
}else if (SqlCommandType.UPDATE.equals(type)) {
typeCode = 2;
}else if (SqlCommandType.INSERT.equals(type)) {
typeCode = 1;
}
// 记录SQL 内容
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
最后修改于 2020-10-20 19:39:31
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

