我的编程空间,编程开发者的网络收藏夹
学习永远不晚

关于MyBatis中Mapper XML热加载优化

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

关于MyBatis中Mapper XML热加载优化

前几天在琢磨mybatis xml热加载的问题,原理还是通过定时扫描xml文件去跟新,但放到项目上就各种问题,由于用了mybatisplus死活不生效。本着"即插即用"的原则,狠心把其中的代码优化了一遍,能够兼容mybatisplus,还加入了一些日志,直接上代码

package com.bzd.core.mybatis;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import com.google.common.collect.Sets;

public class MapperRefresh implements java.lang.Runnable {

    public static Logger log = LoggerFactory.getLogger(MapperRefresh.class);
    private static String filename = "mybatis-refresh.properties";
    private static Properties prop = new Properties();

    private static boolean enabled;         // 是否启用Mapper刷新线程功能
    private static boolean refresh;         // 刷新启用后,是否启动了刷新线程

    private Set<String> location;         // Mapper实际资源路径

    private Resource[] mapperLocations;     // Mapper资源路径
    private Configuration configuration;        // MyBatis配置对象

    private Long beforeTime = 0L;           // 上一次刷新时间
    private static int delaySeconds;        // 延迟刷新秒数
    private static int sleepSeconds;        // 休眠时间
    private static String mappingPath;      // xml文件夹匹配字符串,需要根据需要修改
    static {

//        try {
//            prop.load(MapperRefresh.class.getResourceAsStream(filename));
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("Load mybatis-refresh “"+filename+"” file error.");
//        }


        URL url = MapperRefresh.class.getClassLoader().getResource(filename);
        InputStream is;
        try {
            is = url.openStream();
            if (is == null) {
                log.warn("applicationConfig.properties not found.");
            } else {
                prop.load(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String value = getPropString("enabled");
        System.out.println(value);
        enabled = "true".equalsIgnoreCase(value);

        delaySeconds = getPropInt("delaySeconds");
        sleepSeconds = getPropInt("sleepSeconds");
        //mappingPath = getPropString("mappingPath");

        delaySeconds = delaySeconds == 0 ? 50 : delaySeconds;
        sleepSeconds = sleepSeconds == 0 ? 3 : sleepSeconds;
        mappingPath = StringUtils.isBlank(mappingPath) ? "mappings" : mappingPath;

        log.debug("[enabled] " + enabled);
        log.debug("[delaySeconds] " + delaySeconds);
        log.debug("[sleepSeconds] " + sleepSeconds);
        log.debug("[mappingPath] " + mappingPath);
    }

    public static boolean isRefresh() {
        return refresh;
    }

    public MapperRefresh(Resource[] mapperLocations, Configuration configuration) {
        this.mapperLocations = mapperLocations;
        this.configuration = configuration;
    }

    @Override
    public void run() {

        beforeTime = System.currentTimeMillis();

        log.debug("[location] " + location);
        log.debug("[configuration] " + configuration);

        if (enabled) {
            // 启动刷新线程
            final MapperRefresh runnable = this;
            new Thread(new java.lang.Runnable() {
                @SneakyThrows
                @Override
                public void run() {

                    

                    try {
                        Thread.sleep(delaySeconds * 1000);
                    } catch (InterruptedException e2) {
                        e2.printStackTrace();
                    }
                    refresh = true;

                    System.out.println("========= Enabled refresh mybatis mapper =========");

                    while (true) {
                        try {
                            log.info("start refresh");
                            List<Resource> res = getModifyResource(mapperLocations,beforeTime);
                            if(res.size()>0)
                                runnable.refresh(res);
                            // 如果刷新了文件,则修改刷新时间,否则不修改
                            beforeTime = System.currentTimeMillis();
                            log.info("end refresh("+res.size()+")");
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                        try {
                            Thread.sleep(sleepSeconds * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, "MyBatis-Mapper-Refresh").start();
        }
    }


    private List<Resource> getModifyResource(Resource[] mapperLocations,long time){

        List<Resource> resources = new ArrayList<>();
        for (int i = 0; i < mapperLocations.length; i++) {
            try {
                if(isModify(mapperLocations[i],time))
                    resources.add(mapperLocations[i]);
            } catch (IOException e) {
                throw new RuntimeException("读取mapper文件异常",e);
            }
        }
        return resources;
    }

    private boolean isModify(Resource resource,long time) throws IOException {
        if (resource.lastModified() > time) {
            return true;
        }
        return false;
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void refresh(List<Resource> mapperLocations) throws Exception {

        // 获取需要刷新的Mapper文件列表
        

        for (int i = 0; i < mapperLocations.size(); i++) {

            Resource resource = mapperLocations.get(i);
            InputStream inputStream = resource.getInputStream();
            System.out.println("refreshed : "+resource.getDescription());
            //这个是mybatis 加载的资源标识,没有绝对标准
            String resourcePath = resource.getDescription();
            try {

                clearMybatis(resourcePath);

                //重新编译加载资源文件。
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(inputStream, configuration,
                        resourcePath, configuration.getSqlFragments());
                xmlMapperBuilder.parse();
            } catch (Exception e) {
                throw new NestedIOException("Failed to parse mapping resource: '" + resourcePath + "'", e);
            } finally {
                ErrorContext.instance().reset();
            }
//            System.out.println("Refresh file: " + mappingPath + StringUtils.substringAfterLast(fileList.get(i).getAbsolutePath(), mappingPath));
            
        }


    }


    private void clearMybatis(String resource) throws NoSuchFieldException, IllegalAccessException {
        // 清理原有资源,更新为自己的StrictMap方便,增量重新加载
        String[] mapFieldNames = new String[]{
                "mappedStatements", "caches",
                "resultMaps", "parameterMaps",
                "keyGenerators", "sqlFragments"
        };
        for (String fieldName : mapFieldNames){
            Field field = configuration.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            Map map = ((Map)field.get(configuration));
            if (!(map instanceof StrictMap)){
                Map newMap = new StrictMap(StringUtils.capitalize(fieldName) + "collection");
                for (Object key : map.keySet()){
                    try {
                        newMap.put(key, map.get(key));
                    }catch(IllegalArgumentException ex){
                        newMap.put(key, ex.getMessage());
                    }
                }
                field.set(configuration, newMap);
            }
        }

        // 清理已加载的资源标识,方便让它重新加载。
        Field loadedResourcesField = configuration.getClass().getDeclaredField("loadedResources");
        loadedResourcesField.setAccessible(true);
        Set loadedResourcesSet = ((Set)loadedResourcesField.get(configuration));
        loadedResourcesSet.remove(resource);
    }

    
    private List<File> getRefreshFile(File dir, Long beforeTime) {
        List<File> fileList = new ArrayList<File>();

        File[] files = dir.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                if (file.isDirectory()) {
                    fileList.addAll(this.getRefreshFile(file, beforeTime));
                } else if (file.isFile()) {
                    if (this.checkFile(file, beforeTime)) {
                        fileList.add(file);
                    }
                } else {
                    System.out.println("Error file." + file.getName());
                }
            }
        }
        return fileList;
    }


    
    private boolean checkFile(File file, Long beforeTime) {
        if (file.lastModified() > beforeTime) {
            return true;
        }
        return false;
    }

    
    private static int getPropInt(String key) {
        int i = 0;
        try {
            i = Integer.parseInt(getPropString(key));
        } catch (Exception e) {
        }
        return i;
    }

    
    private static String getPropString(String key) {
        return prop == null ? null : prop.getProperty(key).trim();
    }

    
    public static class StrictMap<V> extends HashMap<String, V> {

        private static final long serialVersionUID = -4950446264854982944L;
        private String name;

        public StrictMap(String name, int initialCapacity, float loadFactor) {
            super(initialCapacity, loadFactor);
            this.name = name;
        }

        public StrictMap(String name, int initialCapacity) {
            super(initialCapacity);
            this.name = name;
        }

        public StrictMap(String name) {
            super();
            this.name = name;
        }

        public StrictMap(String name, Map<String, ? extends V> m) {
            super(m);
            this.name = name;
        }

        @SuppressWarnings("unchecked")
        public V put(String key, V value) {
            // ThinkGem 如果现在状态为刷新,则刷新(先删除后添加)
            if (MapperRefresh.isRefresh()) {
                remove(key);
//                MapperRefresh.log.debug("refresh key:" + key.substring(key.lastIndexOf(".") + 1));
            }
            // ThinkGem end
            if (containsKey(key)) {
                throw new IllegalArgumentException(name + " already contains value for " + key);
            }
            if (key.contains(".")) {
                final String shortKey = getShortName(key);
                if (super.get(shortKey) == null) {
                    super.put(shortKey, value);
                } else {
                    super.put(shortKey, (V) new Ambiguity(shortKey));
                }
            }
            return super.put(key, value);
        }

        public V get(Object key) {
            V value = super.get(key);
            if (value == null) {
                throw new IllegalArgumentException(name + " does not contain value for " + key);
            }
            if (value instanceof Ambiguity) {
                throw new IllegalArgumentException(((Ambiguity) value).getSubject() + " is ambiguous in " + name
                        + " (try using the full name including the namespace, or rename one of the entries)");
            }
            return value;
        }

        private String getShortName(String key) {
            final String[] keyparts = key.split("\\.");
            return keyparts[keyparts.length - 1];
        }

        protected static class Ambiguity {
            private String subject;

            public Ambiguity(String subject) {
                this.subject = subject;
            }

            public String getSubject() {
                return subject;
            }
        }
    }
}

这里提供两种配置方式一种是springboot,一种就是普通的spring项目

1.springboot 方式 就是

package com.bzd.bootadmin.conf;

import com.bzd.core.mybatis.MapperRefresh;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import javax.annotation.PostConstruct;

@Configuration
@MapperScan(value = {"com.bzd.bootadmin.modular.index.mapper"})
public class MybatisConfig {


    @Autowired
    SqlSessionFactory factory;

    @Autowired
    MybatisProperties properties;

    @PostConstruct
    public void postConstruct()  {
        Resource[] resources =  this.properties.resolveMapperLocations();
        new MapperRefresh(resources, factory.getConfiguration()).run();
    }



}

2:普通spring项目


import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.core.io.Resource;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class RefreshStarter {

    SqlSessionFactory factory;

    Resource[] mapperLocations;

    @PostConstruct
    public void postConstruct() throws IOException {
        Resource[] resources = mapperLocations;
        enableMybatisPlusRefresh(factory.getConfiguration());
        new MapperRefresh(resources, factory.getConfiguration()).run();
    }


    
    public void enableMybatisPlusRefresh(Configuration configuration){


        try {
            Method method = Class.forName("com.baomidou.mybatisplus.toolkit.GlobalConfigUtils")
                    .getMethod("getGlobalConfig", Configuration.class);
            Object globalConfiguration = method.invoke(null, configuration);
            method = Class.forName("com.baomidou.mybatisplus.entity.GlobalConfiguration")
                    .getMethod("setRefresh", boolean.class);
            method.invoke(globalConfiguration, true);
        } catch (ClassNotFoundException e) {

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    public SqlSessionFactory getFactory() {
        return factory;
    }

    public void setFactory(SqlSessionFactory factory) {
        this.factory = factory;
    }

    public Resource[] getMapperLocations() {
        return mapperLocations;
    }

    public void setMapperLocations(Resource[] mapperLocations) {
        this.mapperLocations = mapperLocations;
    }
}

在xml中配置

	<bean  class="com.foxtail.core.mybatis.RefreshStarter">
		<property name="mapperLocations">
			<array>
				<value>classpath:com/foxtail/mapping/*/*.xml</value>
				<value>classpath:com/foxtail/mapping/*.xml</value>
			</array>
		</property>
		<property name="factory" ref="sqlSessionFactory" />
	</bean>

最后在resources中加入mybatis-refresh.properties

#是否开启刷新线程  
enabled=true  
#延迟启动刷新程序的秒数  
delaySeconds=5 
#刷新扫描间隔的时长秒数  
sleepSeconds=3  

到这里就大功告成了,最后加到代码里面有没有生效呢,改完sql之后总会想到底是更新了还是没更新,又看不到,这是程序员最头疼的。因为加了日志都不用担心啦

在这里插入图片描述

到此这篇关于关于MyBatis中Mapper XML热加载优化的文章就介绍到这了,更多相关MyBatis Mapper XML热加载内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

关于MyBatis中Mapper XML热加载优化

下载Word文档到电脑,方便收藏和打印~

下载Word文档

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录