MyBatis热部署
代码
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Repository;
/**
* 定时扫描并动态加载mybatis的SQL配置文件,刷新sql mapper cache,可以在修改xml后不用重启tomcat也能生效
*
* 扫描参数:<br/>
* 1.RELOAD_INTERVAL:扫描时间间隔=3s<br/>
* 2.XML_RESOURCE_PATTERN:当前CLASSPATH下xml通配符<br/>
* 3.SESSION_FACTORY_BEAN_NAME:数据源session factory名称<br/>
* 备注:本类在开发环境下使用,正式发布后注释掉applicationContext.xml中id=MyBatisDynamicLoader的bean
*
* @author MF
* @version 1.0
*/
@Repository("XMLMapperLoader")
public class XMLMapperLoader implements InitializingBean, ApplicationContextAware {
// 扫描时间间隔
private static final long RELOAD_INTERVAL = 3000;
private final HashMap<String, String> mappers = new HashMap<String, String>();
private volatile ConfigurableApplicationContext context = null;
private volatile Scanner scanner = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = (ConfigurableApplicationContext) applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
try {
scanner = new Scanner();
new Timer(true).schedule(new TimerTask() {
public void run() {
try {
if (scanner.isChanged()) {
scanner.reloadXML();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 5 * 1000, RELOAD_INTERVAL);
} catch (Exception e1) {
e1.printStackTrace();
}
}
class Scanner {
private static final String XML_RESOURCE_PATTERN =
ResourcePatternResolver.CLASSPATH_URL_PREFIX + "mapper/*/*.xml";
private static final String SESSION_FACTORY_BEAN_NAME = "sqlSessionFactory";
private final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
public Scanner() throws IOException {
Resource[] resources = findResource();
if (resources != null) {
for (Resource resource : resources) {
String key = resource.getURI().toString();
String value = getMd(resource);
mappers.put(key, value);
}
}
}
public void reloadXML() throws Exception {
// 如果是单数据源用这个
// SqlSessionFactory factory = context.getBean(SqlSessionFactory.class);
/* 这里指定数据源,多数据源环境使用 */
System.out.println("========== Reload SQL Cache on [" + SESSION_FACTORY_BEAN_NAME + "] ==========");
SqlSessionFactory factory = (SqlSessionFactory) context.getBean(SESSION_FACTORY_BEAN_NAME);
Configuration configuration = factory.getConfiguration();
removeConfig(configuration);
for (Resource resource : findResource()) {
System.out.println(resource.getFilename());
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(), configuration,
resource.toString(), configuration.getSqlFragments());
xmlMapperBuilder.parse();
} finally {
ErrorContext.instance().reset();
}
}
System.out.println("========== Reload end ==========");
}
private void removeConfig(Configuration configuration) throws Exception {
Class<?> classConfig = configuration.getClass();
clearMap(classConfig, configuration, "mappedStatements");
clearMap(classConfig, configuration, "caches");
clearMap(classConfig, configuration, "resultMaps");
clearMap(classConfig, configuration, "parameterMaps");
clearMap(classConfig, configuration, "keyGenerators");
clearMap(classConfig, configuration, "sqlFragments");
clearSet(classConfig, configuration, "loadedResources");
}
@SuppressWarnings("rawtypes")
private void clearMap(Class<?> classConfig, Configuration configuration, String fieldName) throws Exception {
Field field = classConfig.getDeclaredField(fieldName);
field.setAccessible(true);
((Map) field.get(configuration)).clear();
}
@SuppressWarnings("rawtypes")
private void clearSet(Class<?> classConfig, Configuration configuration, String fieldName) throws Exception {
Field field = classConfig.getDeclaredField(fieldName);
field.setAccessible(true);
((Set) field.get(configuration)).clear();
}
public boolean isChanged() throws IOException {
boolean isChanged = false;
for (Resource resource : findResource()) {
String key = resource.getURI().toString();
String value = getMd(resource);
if (!value.equals(mappers.get(key))) {
isChanged = true;
mappers.put(key, value);
}
}
return isChanged;
}
private Resource[] findResource() throws IOException {
return resourcePatternResolver.getResources(XML_RESOURCE_PATTERN);
}
private String getMd(Resource resource) throws IOException {
return new StringBuilder()
.append(resource.contentLength())
.append("-")
.append(resource.lastModified())
.toString();
}
}
}
Spring加载方式
加载方式:在Spring XML文件中加入:(发布生产时要注释掉,不启动)
<!-- MyBatis 热加载,修改无需重新部署web容器的bean -->
<bean id ="MyBatisDynamicLoader" class= "com.xxx.XMLMapperLoader"/>
MyBatis热部署的更多相关文章
- MyBatis-HotSwap, MyBatis热部署
https://github.com/xiaochenxinqing/MyBatis-HotSwap 1 https://github.com/xiaochenxinqing/MyBatis-Ho ...
- mybatis 热部署xml文件(spring boot和springmvc两种方式)
参考:http://thinkgem.iteye.com/blog/2304557 步骤:1.创建两个java类 (1)MapperRefresh.java :用于刷新mapper (2)SqlS ...
- springboot集成mybatis(逆向工程),热部署以及整合Swagger2
本文是作者原创,版权归作者所有.若要转载,请注明出处. springboot集成mybatis和mybatis-generator插件 1.新建Springboot项目(略) 2.导入相关依赖 < ...
- springboot整合mybatis增删改查(二):springboot热部署
SpringBoot整合热部署 传统情况下, 我们用idea运行springboot程序时, 如果我们需要修改类里的方法,或者其他信息 我们需要修改完保存,并且重启springboot,有时候会很浪费 ...
- SpringBoot+gradle+idea实现热部署和热加载
前言 因为之前使用myeclipes的同学就知道,在使用myeclipes的时候,java文件或者jsp文件写完之后会被直接热加载到部署的容器中,从而在开发的时候,不同经常去重启项目,从而达到了增加开 ...
- SpringBoot03 项目热部署
1 问题 在编写springBoot项目时,经常需要修改代码:但是每次修改代码后都需重新启动,修改的代码才会生效 2 这么实现IDEA能够像Eclipse那样保存过后就可以自动进行刷新呢 将sprin ...
- SpringBoot实现热部署(修改class不需要重启)
热部署: devtools可以实现页面热部署(即页面修改后会立即生效, 这个可以直接在application.properties文件中配置spring.thymeleaf.cache=false来实 ...
- SpringBoot热部署的实现方式
一:热部署的实现 1.使用Spring-boot-devtools 2.使用Spring Loaded 二:devtools(推荐) 一般情况下直接在pom.xml文件添加下面的依赖即可,但eclip ...
- IDEA 热部署- 自动编译设置
原文:https://www.cnblogs.com/TechSnail/p/7690829.html && https://blog.csdn.net/qq_3129357 ...
随机推荐
- .NET面试经典三问:什么是.NET?什么是.NET Framework?什么是.NET Core?
什么是.NET?什么是.NET Framework? 本文将从上往下,循序渐进的介绍一系列相关.NET的概念,先从类型系统开始讲起,我将通过跨语言操作这个例子来逐渐引入一系列.NET的相关概念,这主要 ...
- 002.MEMS应用在开关电源上,实现大功率超小型化
设计任务书 1.有关MEMS还有待具体了解 2.有关开关电源的目前难题也需要了解
- React+Webpack+ES6 兼容低版本浏览器(IE9)解决方案
虽然过了兼容IE6的噩梦时代,IE依旧阴魂不散,因为你可能还要兼容IE9.在ES6已经普及的今天,用ES6写react已经成了标配.但是babel编译的js语法,由于某些不规范的写法,可能在IE9下不 ...
- 来扯点ionic3[7] LocalStorage的使用—以登录和注销为例
一般意义上,一个互联网 APP 中的数据主自与服务器的交互,但是对于有些数据,我们希望获取到它们以后能保存,并在全局环境使用,比如用户数据--我们不希望在每个页面都从服务器拉取一遍.这时我们就可以利用 ...
- 2022DASCTF X SU 三月春季挑战赛 Calc
查看代码 #coding=utf-8 from flask import Flask,render_template,url_for,render_template_string,redirect,r ...
- Go 里面的 ^ 和 &^
这几天在研究 Go 的源码,突然发现了一个之前没有见过的位运算,见这里 new &^= mutexWoken & 和 ^,分别表示 AND 和 XOR,这个不用多说. 值得一提的是 ^ ...
- Spark项目应用-电子商务大数据分析总结
一. 数据采集(要求至少爬取三千条记录,时间跨度超过一星期)数据采集到本地文件内容 爬取详见:python爬取京东评论 爬取了将近20000条数据,156个商品种类,用时2个多小时,期间中断数 ...
- java中接口interface有什么用呢?举例!
接口只有方法的定义,没有方法的任何实现.那这有什么意义呢?马克-to-win: 接口就像一个服务合同.接口只关心必须得干什么而不关心如何去实现它.有 意义吗?有意义.马克-to-win:比如我们的软件 ...
- spring security简介与使用
目录 spring security 新建一个springboot项目 添加spring security 登录 使用默认用户和随机生成的密码登录 使用yaml文件定义的用户名.密码登录 使用代码中指 ...
- 两数之和_LeetCode_1
LeetCode_1原题链接:https://leetcode-cn.com/problems/two-sum/ 剑指 Offer 57原题链接: https://leetcode-cn.com/pr ...