java 配置文件修改监控(转)

本文介绍如何利用log4j中的FileWatchdog类来监控配置文件的变化,并在文件发生改变时触发重新加载操作。通过继承FileWatchdog并重写其方法,可以轻松实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原地址:http://blog.sina.com.cn/s/blog_6542ec7b0100i761.html
用java写服务程序时经常会涉及到监控某些配置文件,当配置文件发生变化时实时重新加载该文件的内容到内存.实际上log4j里有现成的类FileWatchdog做了类似的工作.我们只需继承它,然后重写它的一些方法就可以了.
示例代码如下:
private static class XMLWatchdog extends FileWatchdog {



public XMLWatchdog() {
//可以在这里加一些初始化的代码
}


public void doOnChange() {
//当文件发生变化时会调用这个方法,我们在这里写重新加载的代码就可以了.
}
}


FileWatchdog的代码也很简单,其实就是起一个线程,每隔固定的时间扫描一次监控的文件.我把代码也贴出来:'


// Contributors: Mathias Bogaert


package org.apache.log4j.helpers;


import java.io.File;
import org.apache.log4j.helpers.LogLog;


public abstract class FileWatchdog extends Thread {



static final public long DEFAULT_DELAY = 60000;

protected String filename;


protected long delay = DEFAULT_DELAY;

File file;
long lastModif = 0;
boolean warnedAlready = false;
boolean interrupted = false;


protected
FileWatchdog(String filename) {
this.filename = filename;
file = new File(filename);
setDaemon(true);
checkAndConfigure();
}



public
void setDelay(long delay) {
this.delay = delay;
}


abstract
protected
void doOnChange();


protected
void checkAndConfigure() {
boolean fileExists;
try {
fileExists = file.exists();
} catch(SecurityException e) {
LogLog.warn("Was not allowed to read check file existance, file:["+
filename+"].");
interrupted = true; // there is no point in continuing
return;
}


if(fileExists) {
long l = file.lastModified(); // this can also throw a SecurityException
if(l > lastModif) { // however, if we reached this point this
lastModif = l; // is very unlikely.
doOnChange();
warnedAlready = false;
}
} else {
if(!warnedAlready) {
LogLog.debug("["+filename+"] does not exist.");
warnedAlready = true;
}
}
}


public
void run() {
while(!interrupted) {
try {
Thread.sleep(delay);
} catch(InterruptedException e) {
// no interruption expected
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值