欢迎支持笔者新作:《深入理解Kafka:核心设计与实践原理》和《RabbitMQ实战指南》,同时欢迎关注笔者的微信公众号:朱小厮的博客。
欢迎跳转到本文原文阅读:https://honeypps.com/java/mybatis-sql-interceptor/
主要功能:通过log4j配置mybatis的打印,只能输出到控制台,而并非真正能够实现sql的获取,本文主要通过拦截器实现sql的拦截,进而对sql进行相应的操作。
起因:因项目需要,服务器要配成双机热备,那么数据库(这里采用的是MySQL)也是双机的,这就牵涉到数据库同步的问题,由于某种原因(这就不透露了)不能采用MySQL自身的同步机制,采用原先C/S系统的同步机制进行同步。
实现方式:mybatis与主数据库正常交互,通过拦截器拦截sql并通过webservice将sql发送到C/S系统的同步模块,进而同步备数据库。
主要代码:
- package com.shr.dao;
-
- import java.text.DateFormat;
- import java.util.Date;
- import java.util.List;
- import java.util.Locale;
- import java.util.Properties;
-
- import java.util.concurrent.ConcurrentLinkedDeque;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
-
- import org.apache.log4j.Logger;
-
- import javax.inject.Inject;
- import javax.inject.Named;
-
- import org.apache.ibatis.executor.Executor;
- import org.apache.ibatis.mapping.BoundSql;
- import org.apache.ibatis.mapping.MappedStatement;
- import org.apache.ibatis.mapping.ParameterMapping;
- import org.apache.ibatis.plugin.Interceptor;
- import org.apache.ibatis.plugin.Intercepts;
- import org.apache.ibatis.plugin.Invocation;
- import org.apache.ibatis.plugin.Plugin;
- import org.apache.ibatis.plugin.Signature;
- import org.apache.ibatis.reflection.MetaObject;
- import org.apache.ibatis.session.Configuration;
- import org.apache.ibatis.session.ResultHandler;
- import org.apache.ibatis.session.RowBounds;
- import org.apache.ibatis.type.TypeHandlerRegistry;
-
- @Intercepts({
- @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }),
- @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
- RowBounds.class, ResultHandler.class }) })
- public class MyBatisSQLInterceptor implements Interceptor {
- private Logger logger = Logger.getLogger(MyBatisSQLInterceptor.class.getSimpleName());
-
- @SuppressWarnings("unused")
- private Properties properties;
-
- private ConcurrentLinkedDeque<String> list = new ConcurrentLinkedDeque<String>();
- // @Inject
- // @Named("soapClient")
- // private SoapClient soapClient;
-
- public MyBatisSQLInterceptor()
- {
- ExecutorService exec = Executors.newSingleThreadExecutor();
- exec.execute(new Thread(){
- public void run(){
- while(true)
- {
- if(list.isEmpty() == false)
- {
- String sql = list.pollFirst();
- logger.info("[SEND WS: ["+sql+"]]");
- //与WebService交互
- }
- try {
- TimeUnit.MILLISECONDS.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- });
-
- exec.shutdown();
- }
-
- public Object intercept(Invocation invocation) throws Throwable {
- MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
- Object parameter = null;
- if (invocation.getArgs().length > 1) {
- parameter = invocation.getArgs()[1];
- }
- BoundSql boundSql = mappedStatement.getBoundSql(parameter);
- Configuration configuration = mappedStatement.getConfiguration();
- Object returnValue = null;
- returnValue = invocation.proceed();
- showSql(configuration, boundSql);
- return returnValue;
- }
-
- private 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(obj) + "'";
- // System.out.println(value);
- } else {
- if (obj != null) {
- value = obj.toString();
- } else {
- value = "";
- }
-
- }
- return value;
- }
-
- public 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();
- 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));
- }
- }
- }
- }
- logger.info(sql);
- if(sql.startsWith("select") == false)
- {
- list.add(sql);
- }
- return sql;
- }
-
- public Object plugin(Object target) {
- return Plugin.wrap(target, this);
- }
-
- public void setProperties(Properties properties0) {
- this.properties = properties0;
- }
- }
欢迎支持笔者新作:《深入理解Kafka:核心设计与实践原理》和《RabbitMQ实战指南》,同时欢迎关注笔者的微信公众号:朱小厮的博客。
欢迎跳转到本文原文阅读:https://honeypps.com/java/mybatis-sql-interceptor/