我如何持久化 Guava AtomicLongMap?
How Do I Persist Guava AtomicLongMap ?
我有这个要求,我需要我的应用程序生成持久序列。通常,我会使用数据库,但不幸的是,我的数据库不支持任何序列。
在这种情况下,我想开发一个 API 以坚持下去,我从 Google 的 Guava 库 - AtomicLongMap 中找到了这个 class正是需要。问题是,我需要我的价值观在重启后保持不变,有什么我可以让它保持不变并在崩溃中幸存下来的吗?
提前致谢,
问候,
由于 java 应用程序在重启后不会 运行,因此您需要 JVM 之外的东西来存储数据。
通常这可以是数据库,但听起来该选项不适合您。
另一种选择是将数据写入文件。当应用程序启动时,它将读取文件并填充 AtomicLongMap。
下面是一个如何读写状态 from/to 文件的示例:
进口
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
从文件读取
@SuppressWarnings("unchecked")
public AtomicLongMap<String> readFromFile(File file) throws IOException, ClassNotFoundException {
try(FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);) {
Map<String,Long>readObj = (Map<String, Long>)ois.readObject();
return AtomicLongMap.create(readObj);
}
}
写入文件
public void writeToFile(AtomicLongMap<String>map, File file) throws IOException {
HashMap<String, Long>newMap = new HashMap<>( map.asMap());
try(FileOutputStream fout = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fout);) {
oos.writeObject(newMap);
}
}
我有这个要求,我需要我的应用程序生成持久序列。通常,我会使用数据库,但不幸的是,我的数据库不支持任何序列。
在这种情况下,我想开发一个 API 以坚持下去,我从 Google 的 Guava 库 - AtomicLongMap 中找到了这个 class正是需要。问题是,我需要我的价值观在重启后保持不变,有什么我可以让它保持不变并在崩溃中幸存下来的吗?
提前致谢, 问候,
由于 java 应用程序在重启后不会 运行,因此您需要 JVM 之外的东西来存储数据。
通常这可以是数据库,但听起来该选项不适合您。
另一种选择是将数据写入文件。当应用程序启动时,它将读取文件并填充 AtomicLongMap。
下面是一个如何读写状态 from/to 文件的示例:
进口
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
从文件读取
@SuppressWarnings("unchecked")
public AtomicLongMap<String> readFromFile(File file) throws IOException, ClassNotFoundException {
try(FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);) {
Map<String,Long>readObj = (Map<String, Long>)ois.readObject();
return AtomicLongMap.create(readObj);
}
}
写入文件
public void writeToFile(AtomicLongMap<String>map, File file) throws IOException {
HashMap<String, Long>newMap = new HashMap<>( map.asMap());
try(FileOutputStream fout = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fout);) {
oos.writeObject(newMap);
}
}