最近接到一个需求,定时获取数据并把数据写入ElasticSearch。
假如每次使用定时启动的时间,每次执行获取一段时间数据,假如每次使用启动成功的时间,会导致数据丢失。
这个时候就考虑对开始时间进行持久化操作。
然后就想到了Properties 对象对数据进行存储。
2、使用方式这里使用了静态方法对对象进行读写。
public static String readProperties(String tempPath,String fileName,String key){
Properties properties = new Properties();
try (FileInputStream inputStream = new FileInputStream(tempPath + fileName)){
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return properties.getProperty(key);
}
public static void writeProperties(String tempPath,String fileName,String key,String value){
Properties properties = new Properties();
try (FileOutputStream outputStream = new FileOutputStream(tempPath + fileName)){
properties.setProperty(key,value);
properties.store(outputStream,"some http request info");
} catch (IOException e) {
e.printStackTrace();
}
}
这里使用了try-with-resource 写法,所以不用关闭流。
对于异常信息,这里没有特殊处理,如果想在项目中使用,可以处理下,例如添加 slf4j 打印等。
批量处理
由于Properties 继承 Hashtable
获取所有数据可以使用:
Listvalues = new ArrayList<>(); Set
当然获取部分数据也可以,这个对key 进行对比就可以。
写入的时候 :
Mapmap = new HashMap<>(); properties.putAll(map);
其他
当然使用的使用也可以转换成HashMap进行操作等:
Properties properties = new Properties(); HashMap3、总结hashMap = new HashMap<>(properties);
对于我本身的业务来讲,其实是找一个地方进行存储,这也是注册中心,数据库等相同的原理。
拿数据库来讲,写入一个非程序本身的地方,下次直接从存储的地方获取。
注册中心是微服务进行注册,其他微服务不用直接调用本服务,达到解耦的目的。
存储文件也是这种思路,写入一个非程序本身的地方,下次直接获取,重启程序不影响已写的数据。



