如何在Hazelcast中为ConcurrentHashMap应用DataSerializable?

时间:2016-09-15 06:56:15

标签: java hazelcast

如何在Hazelcast中为ConcurrentHashMap应用DataSerializable? public class User实现DataSerializable {     public User(){     }     私人约会日期;     私人长身份;     @覆盖      public void writeData(ObjectDataOutput out)throws IOException {         out.writeLong(this.date.getTime());         out.writeLong(this.id);      }      @覆盖      public void readData(ObjectDataInput in)throws IOException {         this.date = new Date(in.readLong());         this.id = in.readLong();      } } <赫兹:序列>     <赫兹:串行>         < hz:serializer type-class =" java.util.concurrent.ConcurrentHashMap"类名="的ConcurrentHashMap"实施=" HashMapStreamSerializer" />     < /赫兹:串行> < /赫兹:序列> 用户user = new User(); user.setId(1L); 地图<长,用户> concurrentHashMap = new ConcurrentHashMap<>(); concurrentHashMap.put(1L,user); iMap.put(1L,concurrentHashMap); // IMap是Hazelcast的分布式地图 我想将concurrentHashMap放到已经实现了DataSerializable的分布式IMap和User类中。 当我运行代码时,我得到了以下异常 com.hazelcast.nio.serialization.HazelcastSerializationException:无法序列化' java.util.concurrent.ConcurrentHashMap'。

1 个答案:

答案 0 :(得分:0)

您可以为未实现DataSerialisable的类实现Custom Serializer

首先,让我们创建一个简单的对象。

public class Employee {
  private String surname;

  public Employee( String surname ) {
    this.surname = surname;
  }
}

现在,让我们为Employee类实现StreamSerializer。

public class EmployeeStreamSerializer
    implements StreamSerializer<Employee> {

  @Override
  public int getTypeId () {
    return 1; 
  }

  @Override
  public void write( ObjectDataOutput out, Employee employee )
      throws IOException { 
    out.writeUTF(employee.getSurname());
  }

  @Override
  public Employee read( ObjectDataInput in ) 
      throws IOException { 
    String surname = in.readUTF();
    return new Employee(surname);
  }

  @Override
  public void destroy () { 
  }
}

这里有完整的例子: http://docs.hazelcast.org/docs/3.7/manual/html-single/index.html#custom-serialization