猿问

如何序列化复杂的磁盘映射?

我有一个简单的内存缓存使用.我希望该缓存在重新启动后继续存在。这意味着,在关机时,我想将内容写入本地磁盘。在应用程序启动时,我想将本地内容读入缓存映射中。ConcurrentHashMap


我不需要在本地磁盘缓存上进行任何查询查找。


//simple key-value store

private final Map<String, Wrapper> cache = new ConcurrentHashMap<>();


public static class Wrapper {

    public List<Transaction> transactions;

    public LocalDateTime timestamp;


    public static class Transaction {

        public String request;

        public String response;

    }

}

问题:你能建议一个现有的库,可以简单地将如此复杂的内容写入/读取到本地文件吗?Map


我考虑过将整个内容序列化为对象,但是由于我需要在应用程序重新启动时读取该缓存,因此性能很重要。使用json可能不是最好的选择。json


白板的微信
浏览 107回答 2
2回答

繁花如伊

您可以编写自己的方法来序列化和反序列化对象。请注意,使用共享资源 IO 库中的 FileUtils 来写入文件和读取文件。public void serializeAndWriteToFile(Object o) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; ByteArrayOutputStream baos = new ByteArrayOutputStream();&nbsp; &nbsp; &nbsp; &nbsp; ObjectOutputStream oos = new ObjectOutputStream(baos);&nbsp; &nbsp; &nbsp; &nbsp; oos.writeObject(o);&nbsp; &nbsp; &nbsp; &nbsp; FileUtils.writeByteArrayToFile(new File("D:\\Test.txt"), baos.toByteArray());&nbsp; &nbsp; } catch (IOException ioe) {&nbsp; &nbsp; &nbsp; &nbsp; // Handle exception&nbsp; &nbsp; }}public void readFromFileAndDeserialize() {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; ByteArrayInputStream bais = new ByteArrayInputStream(FileUtils.readFileoByteArray(new File("D:\\Test.txt")));&nbsp; &nbsp; &nbsp; &nbsp; ObjectInutStream ois = ne ObjectInutStream(bais);&nbsp; &nbsp; &nbsp; &nbsp; Object o = ois.readObject();&nbsp; &nbsp; &nbsp; &nbsp; // Type cast o to your object before using it&nbsp; &nbsp; } catch (IOException | ClassNotFoundException e) {&nbsp; &nbsp; &nbsp; &nbsp; // Handle exception&nbsp; &nbsp; }}

HUX布斯

你可以看看MapDB。它完全符合您的要求。
随时随地看视频慕课网APP

相关分类

Java
我要回答