序列化:將對象狀態轉為字節流(持久化/網絡傳輸)
反序列化:字節流還原為對象
Serializable 標記接口serialVersionUID(強烈建議顯式聲明)ObjectOutputStream.writeObject() / ObjectInputStream.readObject()// 實體類
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String id, name;
// getter/setter/構造器
}
// 序列化
try (FileOutputStream fos = new FileOutputStream("d:/student");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(new Student("201441413110", "yang"));
}
// 反序列化
try (FileInputStream fis = new FileInputStream("d:/student");
ObjectInputStream ois = new ObjectInputStream(fis)) {
Student stu = (Student) ois.readObject();
System.out.println(stu.getId() + " " + stu.getName());
}
AC ED + 版本 00 05serialVersionUID針對分布式場景優化:
DataInput/DataOutput,避免反射WritableComparable,MapReduce Shuffle 階段零拷貝比較// 基礎接口
public interface Writable {
void write(DataOutput out) throws IOException;
void readFields(DataInput in) throws IOException;
}
// 可比較接口(MapReduce Key 必須)
public interface WritableComparable<T> extends Writable, Comparable<T> {}
// 高效比較器(無需反序列化即可比較字節流)
public interface RawComparator<T> extends Comparator<T> {
int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2);
}
// 通用實現工廠
RawComparator<IntWritable> cmp = WritableComparator.get(IntWritable.class);
public class Serialize {
public static byte[] serialize(Writable w) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(out);
w.write(dos);
dos.close();
return out.toByteArray();
}
public static void deserialize(Writable w, byte[] bytes) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(in);
w.readFields(dis);
dis.close();
}
public static void main(String[] args) throws IOException {
IntWritable src = new IntWritable(20);
IntWritable dest = new IntWritable();
deserialize(dest, serialize(src));
System.out.println(dest.get()); // 20
}
}
org.apache.hadoop.io.serializer 包提供插件化機制:
Serialization<T>:判斷類型支持、產出 Serializer/DeserializerWritableSerialization:Writable 類型的默認實現| 維度 | Java Serialization | Hadoop Writable |
|---|---|---|
| 字節體積 | 大(含類名、UID、引用結構) | 小(僅有效負載) |
| 隨機訪問 | 不支持(流式讀取) | 支持(定長/可分片) |
| 排序性能 | 需全反序列化後比較 | RawComparator 直接比較字節 |
| 對象重用 | 每次 new Object | readFields 復用對象 |
| 跨語言 | 困難 | 困難(同屬 JVM 生態) |