使用反射和动态代理实现mybaits的mapping.xml热部署

package com.apexsoft.citic.managed.assistance.module.backdoor.service;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


@Service
public class BackdoorService {

    private static Logger log = Logger.getLogger(BackdoorService.class);

    @Resource
    SqlSession sqlSession;

    private static long lastRefreshMapperTime = System.currentTimeMillis();
    private static boolean isModifiedStrictMapOfConfiguration = false;

    public Set<String> refreshMappper() throws NoSuchFieldException, IllegalAccessException, IOException {
        long startRefreshMapperTime = System.currentTimeMillis();
        Configuration configuration = sqlSession.getConfiguration();
        Field loadedResourcesField = configuration.getClass().getDeclaredField("loadedResources");
        loadedResourcesField.setAccessible(true);
        Set<String> loadedResources = (Set<String>) loadedResourcesField.get(configuration);
        Set<String> loadedResourcesBak = new HashSet<String>(loadedResources);
        Set<String> refreshedResources = new HashSet<String>();
        for (String resource : loadedResourcesBak) {
            if (resource.endsWith(".xml") && isNeedRefresh(resource)) {
                loadedResources.remove(resource);
                if(!isModifiedStrictMapOfConfiguration){
                    modifyStrictMapOfConfiguration(configuration);
                }
                //使用classloader.getResource().openStream() 可以清除缓存
                InputStream inputStream = Thread.currentThread().getContextClassLoader().getResource(resource).openStream();
                XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
                mapperParser.parse();
                refreshedResources.add(resource);
            }
        }
        lastRefreshMapperTime = startRefreshMapperTime;
        return refreshedResources;
    }

    private synchronized void modifyStrictMapOfConfiguration(Configuration configuration) throws NoSuchFieldException, IllegalAccessException {
        if (!isModifiedStrictMapOfConfiguration){
            isModifiedStrictMapOfConfiguration = true;
            // 清理原有资源,更新为自己的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));
                InvocationHandler invocationHandler = new StrictMapInvocationHandler(map);
                Map mapProxy = (Map)Proxy.newProxyInstance(map.getClass().getClassLoader(), map.getClass().getSuperclass().getInterfaces(), invocationHandler);
                field.set(configuration, mapProxy);
            }
        }
    }
    
    private boolean isNeedRefresh(String resource) {
        String nodepath = this.getClass().getClassLoader().getResource("/").getPath();
        File file = new File(nodepath + resource);
        if (file.lastModified() < lastRefreshMapperTime) {
            return false;
        }
        return true;
    }

    protected class StrictMapInvocationHandler implements InvocationHandler{

        private Map target;

        public StrictMapInvocationHandler(Map target){
            super();
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if(method.getName().equals("put")){
                String key = args[0].toString();
                target.remove(key);
                log.info("refresh key:" + key.substring(key.lastIndexOf(".") + 1));
            }
            return method.invoke(target, args);
        }
    }
}

ps: 目前代码只是实现了mapping.xml的重新加载,可以作为java热部署技术的补充

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值