Hazelcast ReplicatedMap序列化到文件中

时间:2016-02-03 14:18:10

标签: java serialization filesystems hazelcast

我正在尝试将ReplicatedMap(hazelcast)保存到文件系统并稍后加载它,但似乎不可能。有什么方法可以实现这个目标吗?

细节:

Map map = HazelcastInstance.getReplicatedMap("map");
File file = new File("hazelcastmap");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(map);
s.close();

抛出的错误是:

java.io.NotSerializableException: com.hazelcast.replicatedmap.impl.ReplicatedMapProxy
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)

有没有办法如何将ReplicatedMap读写到文件中。

谢谢大家。

1 个答案:

答案 0 :(得分:0)

由于ReplicatedMap是一个旨在保留对象引用的结构,因此您必须编写自己的代码以将ReplicatedMap的信息序列化为文件。下面是一个粗略的例子,以(非常)老式的方式做到这一点

private static void writeToFile(){

    // Retrieve your hazelcast reference
    // hazelcast = ...

    Map<Object, Object> map = hazelcast.getReplicatedMap("map");

    FileOutputStream fos = new FileOutputStream("/tmp/out.data");

    ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
    DataOutputStream dataOut = new DataOutputStream(arrayOut);

    dataOut.writeInt(map.size());

    for (Entry<Object, Object> entry : map.entrySet()){

        dataOut.writeUTF(entry.getKey().toString());
        dataOut.writeUTF(entry.getValue().toString());
    }

    fos.write(arrayOut.toByteArray());

    //..close streams
}

private static void readFromFile() throws Exception{

    FileInputStream fis = new FileInputStream("/tmp/out.data");
    DataInputStream dataIn = new DataInputStream(fis);

    Map<Object, Object> map = hazelcast.getReplicatedMap("map");

    int size = dataIn.readInt();

    for (int i = 0; i < size; i++){

        String key = dataIn.readUTF();
        String value = dataIn.readUTF();

        //Convert the String 'value' into your Object
        //put the pair key value into the map
    }

    //..close streams
}