服務(wù)器監(jiān)控狗 log4j FileWatchdog 臨控環(huán)境變化 方便多了
Posted on 2012-02-17 14:03 云云 閱讀(3559) 評(píng)論(0) 編輯 收藏用java寫服務(wù)程序時(shí)經(jīng)常會(huì)涉及到監(jiān)控某些配置文件,當(dāng)配置文件發(fā)生變化時(shí)實(shí)時(shí)重新加載該文件的內(nèi)容到內(nèi)存.
實(shí)際上log4j里有現(xiàn)成的類FileWatchdog做了類似的工作.我們只需繼承它,然后重寫它的一些方法就可以了.
/**使用log4j的監(jiān)控狗 */
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的代碼也很簡單,其實(shí)就是起一個(gè)線程,每隔固定的時(shí)間掃描一次監(jiān)控的文件.我把代碼也貼出來:'


// 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();
}
}
}

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



































































































