死机简单配置
編寫整個框架的目的是為了處理應用程序的配置。 我更喜歡一種簡單的方法。
如果通過配置我們的意思是“ 部署之間可能有所不同的所有內容 ”,那么我們應該嘗試使配置保持簡單。 在Java中,最簡單的選項是不起眼的屬性文件。 屬性文件的缺點是,當您希望應用程序接收更改時必須重新啟動它。 還是你
這是我在多個項目中使用的一種簡單方法:
AppConfiguration類如下所示:
public abstract class AppConfiguration {private static Logger log = LoggerFactory.getLogger(AppConfiguration.class);private long nextCheckTime = 0;private long lastLoadTime = 0;private Properties properties = new Properties();private final File configFile;protected AppConfiguration(String filename) {this.configFile = new File(filename);}public String getProperty(String propertyName, String defaultValue) {String result = getProperty(propertyName);if (result == null) {log.trace("Missing property {} in {}", propertyName, properties.keySet());return defaultValue;}return result;}public String getRequiredProperty(String propertyName) {String result = getProperty(propertyName);if (result == null) {throw new RuntimeException("Missing property " + propertyName);}return result;}private String getProperty(String propertyName) {if (System.getProperty(propertyName) != null) {log.trace("Reading {} from system properties", propertyName);return System.getProperty(propertyName);}if (System.getenv(propertyName.replace('.', '_')) != null) {log.trace("Reading {} from environment", propertyName);return System.getenv(propertyName.replace('.', '_'));}ensureConfigurationIsFresh();return properties.getProperty(propertyName);}private synchronized void ensureConfigurationIsFresh() {if (System.currentTimeMillis() < nextCheckTime) return;nextCheckTime = System.currentTimeMillis() + 10000;log.trace("Rechecking {}", configFile);if (!configFile.exists()) {log.error("Missing configuration file {}", configFile);}if (lastLoadTime >= configFile.lastModified()) return;lastLoadTime = configFile.lastModified();log.debug("Reloading {}", configFile);try (FileInputStream inputStream = new FileInputStream(configFile)) {properties.clear();properties.load(inputStream);} catch (IOException e) {throw new RuntimeException("Failed to load " + configFile, e);}} }這樣可以高效地讀取配置文件,并根據需要更新設置。 它支持默認的環境變量和系統屬性。 而且它甚至可以很好地記錄正在發生的事情。
- 有關完整的源代碼和自動更新的不可思議的數據源,請參見以下要點:https://gist.github.com/jhannes/b8b143e0e5b287d73038
請享用!
翻譯自: https://www.javacodegeeks.com/2014/10/dead-simple-configuration.html
總結
- 上一篇: 草船借箭人物特点 草船借箭人物特点是什么
- 下一篇: 对象应该是不可变的