ITeye博客

用apache的configuration实现实时配置

steven_cheng · 2006-03-24 06:34 · java · Markdown

apache下commons有一个configeration包,对于做配置很方便,尤其是实时热配置。可以自动监测到配置文件的更改而reload配置文件。在项目中使用所以进行了一下封装。

java 代码

  1. public class DefaultRealTimeXMLConfiger {
  2. private static Log logger = LogFactory.getLog(DefaultRealTimeXMLConfiger.class);
  3. private String fileName;
  4. private long reloadPeriod;
  5. private XMLConfiguration config;
  6. public void init()
  7. {
  8. String filePath = GlobalConfigerImpl.getConfDir()+"/"+fileName;
  9. logger.debug("will config with XML file["+filePath+"]");
  10. File file = new File(filePath);
  11. if (!file.exists() || !file.isFile()) {
  12. logger.error(" can't find file[" + filePath + "]");
  13. throw new IllegalArgumentException("config error! can't find file[" + filePath + "]");
  14. }
  15. this.init(file);
  16. }
  17. public void init(File file) {
  18. try {
  19. config = new XMLConfiguration(file);
  20. FileChangedReloadingStrategy fs = new FileChangedReloadingStrategy();
  21. fs.setConfiguration(config);
  22. if(this.reloadPeriod>0)
  23. {
  24. fs.setRefreshDelay(this.reloadPeriod);
  25. }
  26. config.setReloadingStrategy(fs);
  27. } catch (ConfigurationException e) {
  28. logger.error("error! configer error["+file.getPath()+"]");
  29. logger.error(e);
  30. e.printStackTrace();
  31. }
  32. }
  33. public Object getProperty(String name) {
  34. Object s = this.config.getProperty(name);
  35. return s;
  36. }
  37. public String getString(String name) {
  38. Object s = this.config.getProperty(name);
  39. String result = null;
  40. if (s != null)
  41. result = (String) s;
  42. return result;
  43. }
  44. public String[] getStringArray(String name) {
  45. String[] target = this.config.getStringArray(name);
  46. return target;
  47. }
  48. /**
  49. * @return Returns the fileName.
  50. */
  51. public String getFileName() {
  52. return fileName;
  53. }
  54. /**
  55. * @param fileName The fileName to set.
  56. */
  57. public void setFileName(String fileName) {
  58. this.fileName = fileName;
  59. }
  60. /**
  61. * @return Returns the reloadPeriod.
  62. */
  63. public long getReloadPeriod() {
  64. return reloadPeriod;
  65. }
  66. /**
  67. * @param reloadPeriod The reloadPeriod to set.
  68. */
  69. public void setReloadPeriod(long reloadPeriod) {
  70. this.reloadPeriod = reloadPeriod;
  71. }
  72. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。