文章目录
  1. Java一些序列化框架的基本使用
    1. 1. Fastjson
    2. 2. Kryo
    3. 3. Protostuff
    4. 4. 总结

[TOC]

Java一些序列化框架的基本使用

最近在学RPC框架相关的原理和实现,需要用到对数据传输的序列化框架,下面做下简单使用。

下面定义一下序列化和反序列的接口,使用kotlin语言。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface Serializer {

/**
* 将对象序列化成字节数组
*/
fun serialize(obj: Any): ByteArray


/**
* 将字节数组反序列化成指定对象
*/
fun <T> deserialize(bytes: ByteArray, clazz: Class<T>): T

}

1. Fastjson

  • 依赖
1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
  • 封装使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class FastJsonSerializer : Serializer {

/**
* 将对象序列化成字节数组
*/
override fun serialize(obj: Any): ByteArray =
JSON.toJSONBytes(obj, SerializerFeature.SortField)

/**
* 将字节数组反序列化成指定对象
*/
override fun <T> deserialize(bytes: ByteArray, clazz: Class<T>): T =
JSON.parseObject(bytes, clazz, Feature.SortFeidFastMatch)

}

2. Kryo

  • 依赖
1
2
3
4
5
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
<version>${kryo.version}</version>
</dependency>
  • 封装使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class kryoSerializer : Serializer {
/**
* 将对象序列化成字节数组
*/
override fun serialize(obj: Any): ByteArray {
val kryo = Kryo()
val baos = ByteArrayOutputStream()
val output = Output(baos)
kryo.writeObject(output, obj)

return output.use {
it.flush()
// 返回baos字节数组
baos.toByteArray()
}
}

/**
* 将字节数组反序列化成指定对象
*/
override fun <T> deserialize(bytes: ByteArray, clazz: Class<T>): T {
val kryo = Kryo()
val bais = ByteArrayInputStream(bytes)
val input = Input(bais)

return input.use {
kryo.readObject(it, clazz)
}
}
}

3. Protostuff

  • 依赖
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>${protostuff.version}</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>${protostuff.version}</version>
</dependency>
  • 封装使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ProtostuffSerializer : Serializer {
/**
* 将对象序列化成字节数组
*/
override fun serialize(obj: Any): ByteArray {
val schema = RuntimeSchema.createFrom(obj.javaClass)
val buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE)
try {
return ProtostuffIOUtil.toByteArray(obj, schema, buffer)
} finally {
buffer.clear()
}
}

/**
* 将字节数组反序列化成指定对象
*/
override fun <T> deserialize(bytes: ByteArray, clazz: Class<T>): T {
val schema = RuntimeSchema.createFrom(clazz)
val message = schema.newMessage()
ProtostuffIOUtil.mergeFrom(bytes, message, schema)
return message
}
}

4. 总结

其他还有诸如ProtobufThrift等等。

序列化框架之间的比较可以参考:https://github.com/eishay/jvm-serializers/wiki

文章目录
  1. Java一些序列化框架的基本使用
    1. 1. Fastjson
    2. 2. Kryo
    3. 3. Protostuff
    4. 4. 总结