Kryo是一个快速有效的对象图序列化Java库。它的目标是快速、高效、易使用。该项目适用于对象持久化到文件或数据库中或通过网络传输。Kryo还可以自动实现深浅的拷贝/克隆。 就是直接复制一个对象对象到另一个对象,而不是对象转换为字节然后转化为对象。

目前已经被用在下列项目中:

KryoNet (NIO networking)

Twitter's Scalding (Scala API for Cascading)

Twitter's Chill (Kryo serializers for Scala)

Apache Fluo (Kryo is default serialization for Fluo Recipes)

Apache Hive (query plan serialization)

Apache Spark (shuffled/cached data serialization)

DataNucleus (JDO/JPA persistence framework)

CloudPelican

Yahoo's S4 (distributed stream computing)

Storm (distributed realtime computation system, in turn used by many others)

Cascalog (Clojure/Java data processing and querying details)

memcached-session-manager (Tomcat high-availability sessions)

Mobility-RPC (RPC enabling distributed applications)

akka-kryo-serialization (Kryo serializers for Akka)

Groupon

Jive

DestroyAllHumans (controls a robot!)

kryo-serializers (additional serializers)

How

Kryo序列化实例:

Kryo kryo = new Kryo();
// ...
Output output = new Output(new FileOutputStream("file.bin"));
SomeClass someObject = ...
kryo.writeObject(output, someObject);
output.close();
// ...
Input input = new Input(new FileInputStream("file.bin"));
SomeClass someObject = kryo.readObject(input, SomeClass.class);
input.close();

Kryo默认为不同的数据类型定义了不同的序列化器,其具体类型如下所示:

col1 col2 col3 col4 col5
boolean Boolean byte Byte char
Character short Short int Integer
long Long float Float double
Double byte[] String BigInteger BigDecimal
Collection Date Collections.emptyList Collections.singleton Map
StringBuilder TreeMap Collections.emptyMap Collections.emptySet KryoSerializable
StringBuffer Class Collections.singletonList Collections.singletonMap Currency
Calendar TimeZone Enum EnumSet

Kryo类在构造参数中会为上述表中的类型初始化对应的序列化类。

其它类会使用默认序列化器FieldSerializer,当然你也可以通过下面的代码更改默认序列化器:

Kryo kryo = new Kryo();
kryo.setDefaultSerializer(AnotherGenericSerializer.class);

也可以为每个类指定序列化类,如下

Kryo kryo = new Kryo();
kryo.register(SomeClass.class, new SomeSerializer());
kryo.register(AnotherClass.class, new AnotherSerializer());

Why

1.下面通过以下Kryo4.0源代码看一下

Kryo类的构造函数为:

public Kryo (ClassResolver classResolver, ReferenceResolver referenceResolver, StreamFactory streamFactory) {
if (classResolver == null) throw new IllegalArgumentException("classResolver cannot be null."); this.classResolver = classResolver;
classResolver.setKryo(this); this.streamFactory = streamFactory;
streamFactory.setKryo(this); this.referenceResolver = referenceResolver;
if (referenceResolver != null) {
referenceResolver.setKryo(this);
references = true;
}
//private final ArrayList<DefaultSerializerEntry> defaultSerializers = new ArrayList(33);用一个大小为33的Entry来存放类及序列化器
addDefaultSerializer(byte[].class, ByteArraySerializer.class);
addDefaultSerializer(char[].class, CharArraySerializer.class);
addDefaultSerializer(short[].class, ShortArraySerializer.class);
addDefaultSerializer(int[].class, IntArraySerializer.class);
addDefaultSerializer(long[].class, LongArraySerializer.class);
addDefaultSerializer(float[].class, FloatArraySerializer.class);
addDefaultSerializer(double[].class, DoubleArraySerializer.class);
addDefaultSerializer(boolean[].class, BooleanArraySerializer.class);
addDefaultSerializer(String[].class, StringArraySerializer.class);
addDefaultSerializer(Object[].class, ObjectArraySerializer.class);
addDefaultSerializer(KryoSerializable.class, KryoSerializableSerializer.class);
addDefaultSerializer(BigInteger.class, BigIntegerSerializer.class);
addDefaultSerializer(BigDecimal.class, BigDecimalSerializer.class);
addDefaultSerializer(Class.class, ClassSerializer.class);
addDefaultSerializer(Date.class, DateSerializer.class);
addDefaultSerializer(Enum.class, EnumSerializer.class);
addDefaultSerializer(EnumSet.class, EnumSetSerializer.class);
addDefaultSerializer(Currency.class, CurrencySerializer.class);
addDefaultSerializer(StringBuffer.class, StringBufferSerializer.class);
addDefaultSerializer(StringBuilder.class, StringBuilderSerializer.class);
addDefaultSerializer(Collections.EMPTY_LIST.getClass(), CollectionsEmptyListSerializer.class);
addDefaultSerializer(Collections.EMPTY_MAP.getClass(), CollectionsEmptyMapSerializer.class);
addDefaultSerializer(Collections.EMPTY_SET.getClass(), CollectionsEmptySetSerializer.class);
addDefaultSerializer(Collections.singletonList(null).getClass(), CollectionsSingletonListSerializer.class);
addDefaultSerializer(Collections.singletonMap(null, null).getClass(), CollectionsSingletonMapSerializer.class);
addDefaultSerializer(Collections.singleton(null).getClass(), CollectionsSingletonSetSerializer.class);
addDefaultSerializer(TreeSet.class, TreeSetSerializer.class);
addDefaultSerializer(Collection.class, CollectionSerializer.class);
addDefaultSerializer(TreeMap.class, TreeMapSerializer.class);
addDefaultSerializer(Map.class, MapSerializer.class);
addDefaultSerializer(TimeZone.class, TimeZoneSerializer.class);
addDefaultSerializer(Calendar.class, CalendarSerializer.class);
addDefaultSerializer(Locale.class, LocaleSerializer.class);
addDefaultSerializer(Charset.class, CharsetSerializer.class);
addDefaultSerializer(URL.class, URLSerializer.class);
OptionalSerializers.addDefaultSerializers(this);
TimeSerializers.addDefaultSerializers(this);
lowPriorityDefaultSerializerCount = defaultSerializers.size(); // Primitives and string. Primitive wrappers automatically use the same registration as primitives.
register(int.class, new IntSerializer());
register(String.class, new StringSerializer());
register(float.class, new FloatSerializer());
register(boolean.class, new BooleanSerializer());
register(byte.class, new ByteSerializer());
register(char.class, new CharSerializer());
register(short.class, new ShortSerializer());
register(long.class, new LongSerializer());
register(double.class, new DoubleSerializer());
register(void.class, new VoidSerializer());
}
  • Kryo:可看做类与序列化类的Map集合
  • ClassResolver :负责类的注册、根据类标识序列化、根据字节码得到类标识
  • ReferenceResolver接口 :当允许引用时,该类用于跟踪已经读写的对象,为写对象提供ID,根据ID读取对象。

    它有两个实现子类:ListReferenceResolver和MapReferenceResolver
  • StreamFactory接口 :基于系统配置提供输入和输出流。

    它有两个实现子类:DefaultStreamFactory和FastestStreamFactory

2.为什么在使用一个类之前先要将Kryo注册一下?

在序列化时写一个类名是低效的,所以用一个ID来替代类名,只需要使用前完成注册即可,代码如下:

//用先一个可用的整型ID来注册该类,如果类已经被注册,那么就返回之前的注册信息类
public Registration register (Class type) {
Registration registration = classResolver.getRegistration(type);
if (registration != null) return registration;
return register(type, getDefaultSerializer(type));
} //和上面的基本一样,只不过是自己定义ID
public Registration register (Class type, int id) {
Registration registration = classResolver.getRegistration(type);
if (registration != null) return registration;
return register(type, getDefaultSerializer(type), id);
}

参考资料

QA

官方文档中有一段话:

Using Unsafe-based IO may result in a quite significant performance boost (sometimes up-to an order of magnitude), depending on your application. In particular, it helps a lot when serializing large primitive arrays as part of your object graphs.

下面是答案:

Unsafe-based IO uses methods from sun.misc.Unsafe for reading and writing from/to memory. Many of those methods map almost 1:1 to processor instructions. Moreover, reading/writing of arrays of native types is executed in bulk instead of doing it element-by-element as it is usually done by Kryo. Together, these features often provide a significant performance boost.

【原】Kryo序列化篇的更多相关文章

  1. 【Spark调优】Kryo序列化

    [Java序列化与反序列化] Java序列化是指把Java对象转换为字节序列的过程:而Java反序列化是指把字节序列恢复为Java对象的过程.序列化使用场景:1.数据的持久化,通过序列化可以把数据永久 ...

  2. 在Spark中自定义Kryo序列化输入输出API(转)

    原文链接:在Spark中自定义Kryo序列化输入输出API 在Spark中内置支持两种系列化格式:(1).Java serialization:(2).Kryo serialization.在默认情况 ...

  3. Spark 性能相关参数配置详解-压缩与序列化篇

    随着Spark的逐渐成熟完善, 越来越多的可配置参数被添加到Spark中来, 本文试图通过阐述这其中部分参数的工作原理和配置思路, 和大家一起探讨一下如何根据实际场合对Spark进行配置优化. 由于篇 ...

  4. Spark优化之三:Kryo序列化

    Spark默认采用Java的序列化器,这里建议采用Kryo序列化提高性能.实测性能最高甚至提高一倍. Spark之所以不默认使用Kryo序列化,可能的原因是需要对类进行注册. Java程序中注册很简单 ...

  5. 在Spark中使用Kryo序列化

    spark序列化  对于优化<网络性能>极为重要,将RDD以序列化格式来保存减少内存占用. spark.serializer=org.apache.spark.serializer.Jav ...

  6. Spark:将RDD[List[String,List[Person]]]中的List[Person]通过spark api保存为hdfs文件时一直出现not serializable task,没办法找到"spark自定义Kryo序列化输入输出API"

    声明:本文转自<在Spark中自定义Kryo序列化输入输出API>   在Spark中内置支持两种系列化格式:(1).Java serialization:(2).Kryo seriali ...

  7. java原生序列化和Kryo序列化性能比较

    简介 最近几年,各种新的高效序列化方式层出不穷,不断刷新序列化性能的上限,最典型的包括: 专门针对Java语言的:Kryo,FST等等 跨语言的:Protostuff,ProtoBuf,Thrift, ...

  8. Spark设置Kryo序列化缓冲区大小

    背景 今天在开发SparkRDD的过程中出现Buffer Overflow错误,查看具体Yarn日志后发现是因为Kryo序列化缓冲区溢出了,日志建议调大spark.kryoserializer.buf ...

  9. Hadoop2源码分析-序列化篇

    1.概述 上一篇我们了解了MapReduce的相关流程,包含MapReduce V2的重构思路,新的设计架构,与MapReduce V1的区别等内容,今天我们在来学习下在Hadoop V2中的序列化的 ...

随机推荐

  1. 毕向东JAVA视频视频讲解(第八课)

    继承的好处: 1,提高了代码的复用性. 2,让类与类之间产生了关系,给第三个特征多态提供了前提. java中支持单继承.不直接支持多继承,但对C++中的多继承机制进行改良. 单继承:一个子类只能有一个 ...

  2. 1.Spring IoC简单例子

    Spring IoC简单例子 1.IHelloMessage.java package com.tony.spring.chapter01; public interface IHelloMessag ...

  3. php模拟用户自动在qq空间发表文章的方法

    我们这里是一个简单的利用php来模拟登录后再到QQ空间发送文章的一个简单的程序,有需要的朋友可以参考,或改进可以给我意见,代码如下: <?php //模拟get post请求函数 http:// ...

  4. 10个提供免费PHP脚本下载的网站

    本文将重点介绍10个PHP脚本的免费资源下载站.之前推荐 <16个下载超酷脚本的热门网站>,这些网站除了PHP脚本,还有JavaScript.Java.Perl.ASP等脚本.如果你已是脚 ...

  5. js判断浏览器类型 js判断ie6不执行

    js判断浏览器类型 $.browser  对象 $.browser.version 浏览器版本 var binfo = ''; if ($.browser.msie) { binfo = " ...

  6. 使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL

    这里使用的是HttpComponents-Client-4.1.2 package com.jadyer.util; import java.io.File; import java.io.FileI ...

  7. Eclipse常见设置及快捷键使用总结(更新中)

    Eclipse中常见设置: 1.Eclipse在保存时设置自动去掉多余的import和格式化代码 路径: window --> preferences --> java --> Ed ...

  8. R: count number of distinct values in a vector

    numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,         453,435,324,34,456,56,567,65,34,435) a & ...

  9. 如何在Ubuntu上安装最新版本的Node.js

    apt-get update apt-get install -y python-software-properties software-properties-common add-apt-repo ...

  10. sql server 数据库 ' ' 附近有语法错误

    昨天做项目时候,遇到标题的问题,代码跟踪把sql 语句 复制出来在数据库执行不了, 然后重新写个一模一样的,然后在 赋值到代码中,还是同样的错误, 就是不知道哪里出现了错误,最后 把 sql 语句写成 ...