1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
| import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.builder.xml.XMLMapperEntityResolver; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.parsing.XPathParser; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.Ordered; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import org.springframework.util.ReflectionUtils; import javax.annotation.PostConstruct; import java.lang.reflect.Field; import java.nio.file.*; import java.util.*; import java.util.stream.Collectors; @Component @Slf4j public class HotLoadingMybatisXMLPostConstructBean implements Ordered { @Autowired private SqlSessionFactory sqlSessionFactory; @Autowired private SqlSessionFactoryBean sqlSessionFactoryBean; @PostConstruct public void init() { new WatchThread().start(); } @Override public int getOrder() { return Integer.MAX_VALUE; } class WatchThread extends Thread { private Resource[] mapperLocations; private Configuration configuration; @Override public void run() { startWatch(); }
private void startWatch() { try { configuration = sqlSessionFactory.getConfiguration(); mapperLocations = (Resource[]) getFieldValue(sqlSessionFactoryBean, "mapperLocations"); WatchService watcher = FileSystems.getDefault().newWatchService(); getWatchPaths().forEach(p -> { try { Paths.get(p).register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); } catch (Exception e) { log.error("ERROR: 注册xml监听事件", e); } }); while (true) { WatchKey watchKey = watcher.take(); Set<String> set = new HashSet<>(); for (WatchEvent<?> event : watchKey.pollEvents()) { set.add(event.context().toString()); }
reloadXml(set); boolean valid = watchKey.reset(); if (!valid) { break; } } } catch (Exception e) { System.out.println("Mybatis的xml监控失败!"); log.info("Mybatis的xml监控失败!", e); } }
private Set<String> getWatchPaths() { Set<String> set = new HashSet<>(); Arrays.stream(getResource()).forEach(r -> { try { log.info("资源路径:{}", r.toString()); set.add(r.getFile().getParentFile().getAbsolutePath()); } catch (Exception e) { log.info("获取资源路径失败", e); throw new RuntimeException("获取资源路径失败"); } }); log.info("需要监听的xml资源: {}", set); return set; }
private Resource[] getResource() {
return mapperLocations; }
private void clearMap(String nameSpace) { log.info("清理Mybatis的namespace={}在mappedStatements、caches、resultMaps、parameterMaps、keyGenerators、sqlFragments中的缓存", nameSpace); Arrays.asList("mappedStatements", "caches", "resultMaps", "parameterMaps", "keyGenerators", "sqlFragments").forEach(fieldName -> { Object value = getFieldValue(configuration, fieldName); if (value instanceof Map) { Map<?, ?> map = (Map) value; List<Object> list = map.keySet().stream().filter(o -> o.toString().startsWith(nameSpace + ".")).collect(Collectors.toList()); log.info("需要清理的元素: {}", list); list.forEach(k -> map.remove((Object) k)); } }); }
private void clearSet(String resource) { log.info("清理mybatis的资源{}在容器中的缓存", resource); Object value = getFieldValue(configuration, "loadedResources"); if (value instanceof Set) { Set<?> set = (Set) value; set.remove(resource); set.remove("namespace:" + resource); } }
private Object getFieldValue(Object obj, String fieldName) { log.info("从{}中加载{}属性", obj, fieldName); try { Field field = ReflectionUtils.findField(obj.getClass(), fieldName); if (field != null) { ReflectionUtils.makeAccessible(field); return ReflectionUtils.getField(field, obj); } else { throw new RuntimeException("ERROR: 未加载到象中的[" + fieldName + "]属性"); } } catch (Exception e) { log.info("ERROR: 加载对象中[{}]", fieldName, e); throw new RuntimeException("ERROR: 加载对象中[" + fieldName + "]", e); } }
private void reloadXml(Set<String> set) { log.info("需要重新加载的文件列表: {}", set); List<Resource> list = Arrays.stream(getResource()) .filter(p -> set.contains(p.getFilename())) .collect(Collectors.toList()); log.info("需要处理的资源路径:{}", list); list.forEach(r -> { try { clearMap(getNamespace(r)); clearSet(r.toString()); XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(r.getInputStream(), configuration, r.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception e) { log.info("ERROR: 重新加载[{}]失败", r.toString(), e); throw new RuntimeException("ERROR: 重新加载[" + r.toString() + "]失败", e); } finally { ErrorContext.instance().reset(); } }); log.info("成功热部署文件列表: {}", set); }
private String getNamespace(Resource resource) { log.info("从{}获取namespace", resource.toString()); try { XPathParser parser = new XPathParser(resource.getInputStream(), true, null, new XMLMapperEntityResolver()); return parser.evalNode("/mapper").getStringAttribute("namespace"); } catch (Exception e) { log.info("ERROR: 解析xml中namespace失败", e); throw new RuntimeException("ERROR: 解析xml中namespace失败", e); } } } }
|