用java寫服務程序時經常會涉及到監控某些配置文件,當配置文件發生變化時實時重新加載該文件的內容到內存.
實際上log4j里有現成的類FileWatchdog做了類似的工作.我們只需繼承它,然后重寫它的一些方法就可以了.
/**使用log4j的監控狗 */
public class IPAccessFileWatchdog extends FileWatchdog {
public IPAccessFileWatchdog(String filename){
super(filename);
}

public void doOnChange() {
List<String> list = IPAccessController.this.loadIPRule(new File(this.filename));
if (list != null) {
IPAccessController.this.ipRule = list.toArray(new String[list.size()]);
} else {
IPAccessController.this.ipRule = null;
}
LogLog.warn("ip access config load completed from file:" + filename);
}
}
}
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
}
checkAndConfigure();
}
}
}

實際上log4j里有現成的類FileWatchdog做了類似的工作.我們只需繼承它,然后重寫它的一些方法就可以了.



































































































