标签:main artifact version object imp 接口 java ring fast
序列化可以解决分布式系统节点间复杂对象传输的问题. 将对象状态转化为可存储或可传输的过程叫序列化, 而反序列化是将其还原成对象的过程.
Java默认的序列化要求实现Serializable
接口.
缺点:
基于XML格式的传输.
缺点:
MessagePack
Protocal Buffer
// 使用了lombok
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car implements Serializable{
// 版本号, java通过此版本号是否一致判断是否可以执行反序列化
// 名称的数据类型必须准确,否则只是相当于定义一个普通的静态变量
public static long serialVersionUID = -1244L;
// 静态变量不序列化
public static int age = 10;
// 用protobuffer的话, 需要field上加Protobuffer的注解
@Protobuf(fieldType = FieldType.INT32,order = 1)
private int wheels;
@Protobuf(fieldType = FieldType.STRING,order = 2)
private String name;
// 瞬时变量, 不被序列化
private transient String desc;
public static void main(String[] args) throws IOException, ClassNotFoundException {
//serializeCar();
Car car = deSerializeCar();
System.out.println(car.age);
System.out.println(car.toString());
}
private static void serializeCar() throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("car")));
Car car = new Car(4, "BMW", "fast....");
objectOutputStream.writeObject(car);
car.age = 12;
objectOutputStream.close();
}
private static Car deSerializeCar() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream;
objectInputStream = new ObjectInputStream(new FileInputStream(new File("car")));
Car car = (Car) objectInputStream.readObject();
return car;
}
}
static final long serialVersionUID = -124L;
序列化版本号, 一致的版本才可以反序列化transient
修饰的变量不序列化// FastJson的序列化和反序列化
String strJson = JSON.toJSONString(object);
Object object = JSON.parse(text);
//Hessian的序列化
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);
hessian2Output.writeObject(object);
//Protobuffer的序列化
Codec<Car> carCodec = ProtobufProxy.create(Car.class, false);
byte[] bytes = carCodec.encode(object);
序列化需要引用相关的包, 下面列出几个.
<!--jackson的序列化包-->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!--fastjson的序列化包-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
<!--Protobuffer的序列化包,由百度封装,增加了易用性-->
<dependency>
<groupId>com.baidu</groupId>
<artifactId>jprotobuf</artifactId>
<version>2.2.5</version>
</dependency>
<!--hessian的序列化包-->
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.51</version>
</dependency>
标签:main artifact version object imp 接口 java ring fast
原文地址:https://www.cnblogs.com/walkinhalo/p/9661424.html