實現動態(tài)監(jiān)聽文件變化冯痢,實現動態(tài)MessageSource

package org.springframework.learning.resource;

import org.springframework.context.ResourceLoaderAware;

import org.springframework.context.support.AbstractMessageSource;

import org.springframework.core.io.DefaultResourceLoader;

import org.springframework.core.io.Resource;

import org.springframework.core.io.ResourceLoader;

import org.springframework.core.io.support.EncodedResource;

import org.springframework.util.StringUtils;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.io.Reader;

import java.nio.file.*;

import java.text.MessageFormat;

import java.util.Locale;

import java.util.Properties;

import java.util.concurrent.ExecutorService;

`import java.util.concurrent.Executors;

/**

\* @author

\* @date 2020/10/15 9:15 下午

*

\* 動態(tài)監(jiān)聽配置文件的變動,實現動態(tài)MessageSource

\* 1. 定位資源位置

\* 2. 初始化properties

\* 3. 實現resolveCode方法

\* 4. 文件監(jiān)聽 @see WatchService

*/

public class DynamicMessageSourceDemoextends AbstractMessageSourceimplements ResourceLoaderAware {

private static final StringFILE_NAME ="messages.properties";

private static final StringRESOURCE_PATH ="/META-INF/i18n/" +FILE_NAME;

private static final StringENCODE ="UTF-8";

private ResourceLoaderresourceLoader;

private final Propertiesproperties;

private final ResourcemessagePropertiesResource;

private final ExecutorServiceexecutorService = Executors.newSingleThreadExecutor();

public DynamicMessageSourceDemo() {

this.messagePropertiesResource = getMessagePropertiesSource();

? this.properties = loadProperties();

? onMessagePropertiesChanged();

}

private void onMessagePropertiesChanged() {

try {

FilemessagePropertiesSourceFile =messagePropertiesResource.getFile();

?? ? PathmessagePropertiesSourcePath =messagePropertiesSourceFile.toPath();

?? ? FileSystemfileSystem = FileSystems.getDefault();

?? ? WatchServicewatchService =fileSystem.newWatchService();

?? ? Pathdir =messagePropertiesSourcePath.getParent();

?? ? dir.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

?? ? executorService.submit(()->{

processMessagePropertiesChanged(watchService);

?? ? });

? }catch (IOExceptione) {

throw new RuntimeException();

? }

}

private void processMessagePropertiesChanged(WatchServicewatchService) {

while (true){

WatchKey watchKey =null;

?? ? try {

watchKey =watchService.take();

?? ? ? if(watchKey.isValid()){

Pathdir = (Path) watchKey.watchable();

?? ? ? for (WatchEventevent : watchKey.pollEvents()) {

PathabsolutePath =dir.resolve((Path)event.context());

?? ? ? ? if("messages.properties".equals(absolutePath.getFileName().toString())){

System.out.println("文件變化" +absolutePath.toString());

?? ? ? ? ? Filefile =absolutePath.toFile();

?? ? ? ? ? PropertiesnewProperties = loadProperties(new FileReader(file));

?? ? ? ? ? synchronized (properties){

properties.clear();

?? ? ? ? ? ? properties.putAll(newProperties);

?? ? ? ? ? }

}

}

}

}catch (Exceptione) {

throw new RuntimeException(e);

?? ? }finally {

if(null!=watchKey){

watchKey.reset();

?? ? ? }

}

}

}

private PropertiesloadProperties() {

EncodedResourceencodedResource =new EncodedResource(messagePropertiesResource, ENCODE);

? try {

return loadProperties(encodedResource.getReader());

? }catch (IOExceptione) {

throw new RuntimeException(e);

? }

}

private ResourcegetMessagePropertiesSource() {

return getResourceLoader().getResource(RESOURCE_PATH);

}

private PropertiesloadProperties(Readerreader) {

Propertiesproperties =new Properties();

? try {

properties.load(reader);

? }catch (IOExceptione) {

throw new RuntimeException(e);

? }finally {

try {

reader.close();

?? ? }catch (IOExceptione) {

throw new RuntimeException(e);

?? ? }

}

return properties;

}

@Override

protected MessageFormatresolveCode(Stringcode, Localelocale) {

StringmessageFormatPattern =properties.getProperty(code);

? if (StringUtils.hasText(messageFormatPattern)) {

return new MessageFormat(messageFormatPattern, locale);

? }

return null;

}

@Override

public void setResourceLoader(ResourceLoaderresourceLoader) {

this.resourceLoader =resourceLoader;

}

public ResourceLoadergetResourceLoader() {

return this.resourceLoader !=null ?this.resourceLoader :new DefaultResourceLoader();

}

public static void main(String[]args)throws InterruptedException {

DynamicMessageSourceDemodemo =new DynamicMessageSourceDemo();

? for(int i=0;i<10000;i++){

Stringmessage =demo.getMessage("name", null, Locale.getDefault());

?? ? System.out.println(message);

?? ? Thread.sleep(1000);

? }

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末油狂,一起剝皮案震驚了整個濱河市寸癌,隨后出現的幾起案子,更是在濱河造成了極大的恐慌磷蛹,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件味咳,死亡現場離奇詭異槽驶,居然都是意外死亡枪眉,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來聂受,“玉大人,你說我怎么就攤上這事棍鳖⊥肼茫” “怎么了?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵医瘫,是天一觀的道長旧困。 經常有香客問我稼锅,道長矩距,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任锥债,我火速辦了婚禮赞弥,結果婚禮上趣兄,老公的妹妹穿的比我還像新娘。我一直安慰自己艇潭,他們只是感情好,可當我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布鲁纠。 她就那樣靜靜地躺著鳍寂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪捍壤。 梳的紋絲不亂的頭發(fā)上鞍爱,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天,我揣著相機與錄音盗扇,去河邊找鬼沉填。 笑死,一個胖子當著我的面吹牛翼闹,可吹牛的內容都是我干的。 我是一名探鬼主播卵沉,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼琼掠!你這毒婦竟也來了停撞?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤艰猬,失蹤者是張志新(化名)和其女友劉穎埋市,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體道宅,經...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡污茵,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了迹蛤。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片襟士。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖箩兽,靈堂內的尸體忽然破棺而出章喉,到底是詐尸還是另有隱情身坐,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布摊唇,位于F島的核電站涯鲁,受9級特大地震影響有序,放射性物質發(fā)生泄漏岛请。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一盅称、第九天 我趴在偏房一處隱蔽的房頂上張望后室。 院中可真熱鬧,春花似錦岸霹、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至皇筛,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間旗笔,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工蝇恶, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留惶桐,地道東北人。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓贿衍,卻偏偏與公主長得像救恨,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子肠槽,可洞房花燭夜當晚...
    茶點故事閱讀 45,033評論 2 355

推薦閱讀更多精彩內容