从定时检测源码中 修改只在配置更新时log4j
`import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import javax.inject.Inject;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.LogLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;
import com.baidu.disconf.client.common.annotations.DisconfFile;
import com.baidu.disconf.client.common.annotations.DisconfUpdateService;
import com.baidu.disconf.client.common.update.IDisconfUpdate;
@service
@DisconfFile(filename = "log4j.properties")
@DisconfUpdateService(classes = { Log4jConfig.class })
public class Log4jConfig implements IDisconfUpdate {
protected static final Logger LOGGER = LoggerFactory.getLogger(Log4jConfig.class);
@Inject
private TestConfig testConfig;
/**
web端 更新后会触发改方法
*/
@override
public void reload() throws Exception {
// 获取log4j文件路径\
System.out.println(testConfig);
URL url = this.getClass().getClassLoader().getResource("log4j.properties");
if (url != null) {
new MyPropertyWatchdog(url.toString());
} else {
LogLog.error("classpath log4j.properties does not exist.");
}
}
public static void main(String[] args) {
URL url = Log4jConfig.class.getClassLoader().getResource("log4j.properties1");
System.out.println(url);
}
/**
description:内部类 重写了 PropertyWatchdog的方法 原本PropertyWatchdog里是初始化一次
然后一个线程不停地检测 我这里去掉了 线程的检测 只更新一次 MyPropertyWatchdog 获取filename路径后获得Properties
这里需要注意PathMatchingResourcePatternResolver获取资源路径的 new File(filename) 这样是不行的
因为文件加锁了 拿不到
*/
class MyPropertyWatchdog {
Properties properties = new Properties();
protected MyPropertyWatchdog(String filename) {
Resource resources = null;
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
try {
Resource[] resourceList = pathMatchingResourcePatternResolver.getResources(filename);
for (Resource resource : resourceList) {
resources = resource;
}
if (resources != null) {
properties.load(resources.getInputStream());
doOnChange();
} else {
LogLog.warn("[" + filename + "] does not exist.");
}
} catch (IOException e1) {
LogLog.error("[" + filename + "] does not exist.");
}
}
/**
*
* description: 拿到log4j属性文件的留 重新更新一次 只能是log4j属性文件 别的属性文件不行
*
*
* @author ex_qianmi
* @see
*/
protected void doOnChange() {
new PropertyConfigurator();
PropertyConfigurator.configure(properties);
}
}
}`