Java热配_java应用热配置实现

在项目中,经常会把.properties文件作为配置文件来读取,当运行时改变这种配置文件时,tomcat等容器并不会重新载入新值,这样就不得不另外想办法来实现。以下是实现的一种方法,仅供参考

//   不断监控文件

while   (m_bIsMonitor)   {

try{

//   判断文件是否已修改了,若已修改过

if   (nModifiedTime   !=   f.lastModified())   {

nModifiedTime   =   f.lastModified();

m_bIsModified   =   true;

//遍历HashMap的key并根据key从配置文件中更新HashMap

it   =   m_hm.keySet().iterator();

file   =   new   FileInputStream(m_szFP);

properties   =   new   Properties();

properties.load(file);

while(it.hasNext()){

szKey=(String)it.next();

szVal=properties.getProperty(szKey);

if   (szVal   !=   null)   {

szVal   =   szVal.trim();

}

m_hm.put(szKey,   szVal);

}

file.close();

}

}catch(IOException   ioe){

System.out.println(this.getClass()+":syscfgfile   path   error!");

ioe.printStackTrace();

}

//   停顿间隔

try   {

sleep(m_nInterval);

}   catch   (InterruptedException   e)   {

e.printStackTrace();

System.out.println(this.getClass()+":Thread   sleep   error!");

}

}

class   A{

private   File   file;

private   Properties   property=new   Properties();

public   A(){

init();

Thread   t=new   Thread(new   Listener());

t.setDaemon(true);

t.start();

}

private   void   init(){

property.load(new   FileInputStream(file));//重新加载文件

}

class   Listener   implements   Runnable{//扫描文件改动

private   long   modifyTime=file.lastModified();

public   void   run(){

while(true){

long   l=file.lastModified();

if(l>modifyTime){

modifyTime=l;

init();

}

Thread.sleep(100);

}

}

}

注意:重新加载文件时要同步,上面的因为Properties本身是线程安全的所以不用同步

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值