ibatis xml Mapper 自动重加载

XMLMapperReLoader


import
 java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.lang.reflect.Field;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;


import org.dom4j.Node;

import org.apache.log4j.Logger;

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.core.io.FileSystemResource;

import org.springframework.core.io.InputStreamResource;

import org.springframework.core.io.Resource;

import org.springframework.orm.ibatis.SqlMapClientFactoryBean;

import org.springframework.orm.ibatis.SqlMapClientTemplate;


import com.gome.cm.util.DynamicDataSource;

import com.gome.cm.util.SpringContextUtil;

import com.gome.cm.util.StringUtils;

import com.gome.cm.util.dom4jXmlParseMgr;

import com.ibatis.sqlmap.client.SqlMapClient;

import com.ibatis.sqlmap.client.SqlMapClientBuilder;


public class XMLMapperReLoader {


    private Logger logger=Logger. getLogger(this.getClass());

   List<Resource> mapperLocations;

   SqlMapClientTemplate sqlMapClientTemplate;

   private  DynamicDataSource mydataSource;

   private final String SQL_MAPPER_PATH="sql-map-config.xml" ;

   private HashMap<String, String> fileMapping = new HashMap<String, String>();

   private Scanner scanner = null;

   private ScheduledExecutorService service = null;



 


   public void afterPropertiesSet() throws Exception {

       try {

           service = Executors. newScheduledThreadPool(1);

           sqlMapClientTemplate = (SqlMapClientTemplate)SpringContextUtil.getBean( "sqlMapClientTemplateMy");

           mydataSource=(DynamicDataSource)SpringContextUtil.getBean( "mydataSource");

           mapperLocations= new ArrayList<Resource>();

           // 触发文件监听事件

           scanner = new Scanner();

           scanner.scan();


           service.scheduleAtFixedRate( new Task(), 5, 5, TimeUnit.SECONDS);


       } catch (Exception e1) {

           e1.printStackTrace();

       }


   }


   class Task implements Runnable {

       @Override

       public void run() {

           try {

               if ( scanner.isChanged()) {

                   logger.info( "*Mapper.xml文件改变,重新加载." );

                   scanner.reloadXML();

                   logger.info( "加载完毕.");

               }

           } catch (Exception e) {

               e.printStackTrace();

           }

       }


   }


    class Scanner {

        public Scanner() {

                   dom4jXmlParseMgr dom4j = new dom4jXmlParseMgr(Thread.currentThread().getContextClassLoader().getResourceAsStream( SQL_MAPPER_PATH));

                   List<Node> nodeList= dom4j.getMuliElementNode("sqlMapConfig/sqlMap");

                    if(StringUtils. listNotEmpty(nodeList)){

                         for (Node node : nodeList) {

                             String resource=dom4j.getElementAttributeValue(node, "resource");

                             Resource ins= new FileSystemResource(Thread.currentThread().getContextClassLoader().getResource(resource).getFile());

                              mapperLocations.add(ins);

                        }

                   }

                   

          

        }


     

        public void reloadXML() throws Exception {

           Field field = SqlMapClientTemplate. class .getDeclaredField("sqlMapClient" );

             field.setAccessible( true);

             SqlMapClient sqlMapClient = (SqlMapClient) field.get(sqlMapClientTemplate);

            Resource configLocation = new InputStreamResource(Thread.currentThread().getContextClassLoader().getResourceAsStream( SQL_MAPPER_PATH));

           /* SqlMapClientFactoryBean beanFactory= new SqlMapClientFactoryBean();

            beanFactory.setDataSource(mydataSource);

            beanFactory.setConfigLocation(configLocation);

            beanFactory.afterPropertiesSet();

             sqlMapClientTemplate.setSqlMapClient(beanFactory.getObject());

          */

            // 刷新缓存

             sqlMapClient.flushDataCache();

             sqlMapClient= SqlMapClientBuilder.buildSqlMapClient(configLocation.getInputStream());

             sqlMapClientTemplate.setSqlMapClient(sqlMapClient);

             sqlMapClientTemplate.afterPropertiesSet();

        }


   

    


        public void scan() throws IOException {

            if (! fileMapping.isEmpty()) {

                return;

            }

            if ( mapperLocations!= null && mapperLocations.size()>0) {

            Resource[] resources= new Resource[mapperLocations.size()];

              resources = (Resource[])mapperLocations.toArray(resources);

                if (resources != null) {

                    for ( int i = 0; i < resources.length; i++) {

                        String multi_key = getValue(resources[i]);

                        fileMapping.put(resources[i].getFilename(), multi_key);

                    }

                }

            }

        }


        private String getValue(Resource resource) throws IOException {

            String contentLength = String.valueOf((resource.contentLength()));

            String lastModified = String.valueOf((resource.lastModified()));

            return new StringBuilder(contentLength).append(lastModified).toString();

        }


        public boolean isChanged() throws IOException {

            boolean isChanged = false;

            if ( mapperLocations!= null && mapperLocations.size()>0) {

                Resource[] resources= new Resource[mapperLocations.size()];

                  resources = (Resource[])mapperLocations.toArray(resources);

                    for ( int i = 0; i < resources. length ; i++) {

                        String name = resources[i].getFilename();

                        String value = fileMapping.get(name);

                        String multi_key = getValue(resources[i]);

                        if (!multi_key.equals(value)) {

                            isChanged = true;

                            fileMapping.put(name, multi_key);

                        }

                    }

                }

            return isChanged;

        }

    }


    public void destroy() throws Exception {

        if ( service != null) {

            service.shutdownNow();

        }

    }




}


转载于:https://my.oschina.net/u/210769/blog/352236

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值