这里面我们介绍一下序列化框架arvo的使用,在kafka中使用的就是这个。

arvo的使用

一、需要通过插件生成Model类方式

一、生成我们的数据模型User.java

我们在resources里面定义即将要生成的User类的avsc结构。user.avsc的内容如下

{
"namespace": "com.linux.huhx.avro",
"type": "record",
"name": "User",
"fields": [
{
"name": "name",
"type": "string"
},
{
"name": "favorite_number",
"type": [
"int",
"null"
]
},
{
"name": "favorite_color",
"type": [
"string",
"null"
]
}
]
}

然后我们在pom.xml添加依赖与avro-maven-plugin插件

<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.8.2</version>
</dependency> <!-- add arvo plugin -->
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>1.8.2</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>schema</goal>
</goals>
<configuration>
<sourceDirectory>${project.basedir}/src/main/resources</sourceDirectory>
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>

运行mvn generate-sources,就可以在arvo目录下面看到生成的User类。内容如下:

/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.linux.huhx.avro; import org.apache.avro.specific.SpecificData;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore; @SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public class User extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -1677175913369996238L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"User\",\"namespace\":\"com.linux.huhx.avro\",\"fields\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"favorite_number\",\"type\":[\"int\",\"null\"]},{\"name\":\"favorite_color\",\"type\":[\"string\",\"null\"]}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } private static SpecificData MODEL$ = new SpecificData(); private static final BinaryMessageEncoder<User> ENCODER =
new BinaryMessageEncoder<User>(MODEL$, SCHEMA$); private static final BinaryMessageDecoder<User> DECODER =
new BinaryMessageDecoder<User>(MODEL$, SCHEMA$); /**
* Return the BinaryMessageDecoder instance used by this class.
*/
public static BinaryMessageDecoder<User> getDecoder() {
return DECODER;
} /**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
*/
public static BinaryMessageDecoder<User> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<User>(MODEL$, SCHEMA$, resolver);
} /** Serializes this User to a ByteBuffer. */
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
} /** Deserializes a User from a ByteBuffer. */
public static User fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
} @Deprecated public java.lang.CharSequence name;
@Deprecated public java.lang.Integer favorite_number;
@Deprecated public java.lang.CharSequence favorite_color; /**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public User() {} /**
* All-args constructor.
* @param name The new value for name
* @param favorite_number The new value for favorite_number
* @param favorite_color The new value for favorite_color
*/
public User(java.lang.CharSequence name, java.lang.Integer favorite_number, java.lang.CharSequence favorite_color) {
this.name = name;
this.favorite_number = favorite_number;
this.favorite_color = favorite_color;
} public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return name;
case 1: return favorite_number;
case 2: return favorite_color;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
} // Used by DatumReader. Applications should not call.
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: name = (java.lang.CharSequence)value$; break;
case 1: favorite_number = (java.lang.Integer)value$; break;
case 2: favorite_color = (java.lang.CharSequence)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
} /**
* Gets the value of the 'name' field.
* @return The value of the 'name' field.
*/
public java.lang.CharSequence getName() {
return name;
} /**
* Sets the value of the 'name' field.
* @param value the value to set.
*/
public void setName(java.lang.CharSequence value) {
this.name = value;
} /**
* Gets the value of the 'favorite_number' field.
* @return The value of the 'favorite_number' field.
*/
public java.lang.Integer getFavoriteNumber() {
return favorite_number;
} /**
* Sets the value of the 'favorite_number' field.
* @param value the value to set.
*/
public void setFavoriteNumber(java.lang.Integer value) {
this.favorite_number = value;
} /**
* Gets the value of the 'favorite_color' field.
* @return The value of the 'favorite_color' field.
*/
public java.lang.CharSequence getFavoriteColor() {
return favorite_color;
} /**
* Sets the value of the 'favorite_color' field.
* @param value the value to set.
*/
public void setFavoriteColor(java.lang.CharSequence value) {
this.favorite_color = value;
} /**
* Creates a new User RecordBuilder.
* @return A new User RecordBuilder
*/
public static com.linux.huhx.avro.User.Builder newBuilder() {
return new com.linux.huhx.avro.User.Builder();
} /**
* Creates a new User RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new User RecordBuilder
*/
public static com.linux.huhx.avro.User.Builder newBuilder(com.linux.huhx.avro.User.Builder other) {
return new com.linux.huhx.avro.User.Builder(other);
} /**
* Creates a new User RecordBuilder by copying an existing User instance.
* @param other The existing instance to copy.
* @return A new User RecordBuilder
*/
public static com.linux.huhx.avro.User.Builder newBuilder(com.linux.huhx.avro.User other) {
return new com.linux.huhx.avro.User.Builder(other);
} /**
* RecordBuilder for User instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<User>
implements org.apache.avro.data.RecordBuilder<User> { private java.lang.CharSequence name;
private java.lang.Integer favorite_number;
private java.lang.CharSequence favorite_color; /** Creates a new Builder */
private Builder() {
super(SCHEMA$);
} /**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(com.linux.huhx.avro.User.Builder other) {
super(other);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[1].schema(), other.favorite_number);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.favorite_color)) {
this.favorite_color = data().deepCopy(fields()[2].schema(), other.favorite_color);
fieldSetFlags()[2] = true;
}
} /**
* Creates a Builder by copying an existing User instance
* @param other The existing instance to copy.
*/
private Builder(com.linux.huhx.avro.User other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[1].schema(), other.favorite_number);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.favorite_color)) {
this.favorite_color = data().deepCopy(fields()[2].schema(), other.favorite_color);
fieldSetFlags()[2] = true;
}
} /**
* Gets the value of the 'name' field.
* @return The value.
*/
public java.lang.CharSequence getName() {
return name;
} /**
* Sets the value of the 'name' field.
* @param value The value of 'name'.
* @return This builder.
*/
public com.linux.huhx.avro.User.Builder setName(java.lang.CharSequence value) {
validate(fields()[0], value);
this.name = value;
fieldSetFlags()[0] = true;
return this;
} /**
* Checks whether the 'name' field has been set.
* @return True if the 'name' field has been set, false otherwise.
*/
public boolean hasName() {
return fieldSetFlags()[0];
} /**
* Clears the value of the 'name' field.
* @return This builder.
*/
public com.linux.huhx.avro.User.Builder clearName() {
name = null;
fieldSetFlags()[0] = false;
return this;
} /**
* Gets the value of the 'favorite_number' field.
* @return The value.
*/
public java.lang.Integer getFavoriteNumber() {
return favorite_number;
} /**
* Sets the value of the 'favorite_number' field.
* @param value The value of 'favorite_number'.
* @return This builder.
*/
public com.linux.huhx.avro.User.Builder setFavoriteNumber(java.lang.Integer value) {
validate(fields()[1], value);
this.favorite_number = value;
fieldSetFlags()[1] = true;
return this;
} /**
* Checks whether the 'favorite_number' field has been set.
* @return True if the 'favorite_number' field has been set, false otherwise.
*/
public boolean hasFavoriteNumber() {
return fieldSetFlags()[1];
} /**
* Clears the value of the 'favorite_number' field.
* @return This builder.
*/
public com.linux.huhx.avro.User.Builder clearFavoriteNumber() {
favorite_number = null;
fieldSetFlags()[1] = false;
return this;
} /**
* Gets the value of the 'favorite_color' field.
* @return The value.
*/
public java.lang.CharSequence getFavoriteColor() {
return favorite_color;
} /**
* Sets the value of the 'favorite_color' field.
* @param value The value of 'favorite_color'.
* @return This builder.
*/
public com.linux.huhx.avro.User.Builder setFavoriteColor(java.lang.CharSequence value) {
validate(fields()[2], value);
this.favorite_color = value;
fieldSetFlags()[2] = true;
return this;
} /**
* Checks whether the 'favorite_color' field has been set.
* @return True if the 'favorite_color' field has been set, false otherwise.
*/
public boolean hasFavoriteColor() {
return fieldSetFlags()[2];
} /**
* Clears the value of the 'favorite_color' field.
* @return This builder.
*/
public com.linux.huhx.avro.User.Builder clearFavoriteColor() {
favorite_color = null;
fieldSetFlags()[2] = false;
return this;
} @Override
@SuppressWarnings("unchecked")
public User build() {
try {
User record = new User();
record.name = fieldSetFlags()[0] ? this.name : (java.lang.CharSequence) defaultValue(fields()[0]);
record.favorite_number = fieldSetFlags()[1] ? this.favorite_number : (java.lang.Integer) defaultValue(fields()[1]);
record.favorite_color = fieldSetFlags()[2] ? this.favorite_color : (java.lang.CharSequence) defaultValue(fields()[2]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
} @SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<User>
WRITER$ = (org.apache.avro.io.DatumWriter<User>)MODEL$.createDatumWriter(SCHEMA$); @Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
} @SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<User>
READER$ = (org.apache.avro.io.DatumReader<User>)MODEL$.createDatumReader(SCHEMA$); @Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
} }

User

二、序列化我们的User类

public static void serializing() throws IOException {
User user1 = new User();
user1.setName("Alyssa");
user1.setFavoriteNumber(256); User user2 = new User("Ben", 7, "red"); User user3 = User.newBuilder()
.setName("Charlie")
.setFavoriteColor("blue")
.setFavoriteNumber(null)
.build(); DatumWriter<User> userDatumWriter = new SpecificDatumWriter<>(User.class);
DataFileWriter<User> dataFileWriter = new DataFileWriter<>(userDatumWriter);
dataFileWriter.create(user1.getSchema(), new File("file/users.avro")); dataFileWriter.append(user1);
dataFileWriter.append(user2);
dataFileWriter.append(user3);
dataFileWriter.close();
}

上面可以看到多种的创建User类的方式,运行上述代码会把User的有一个实例序列化到文件file/users.avro中。

三、反序列化我们的User类

public static void deserializing() throws IOException {
// Deserialize Users from disk
DatumReader<User> userDatumReader = new SpecificDatumReader<>(User.class);
DataFileReader<User> dataFileReader = new DataFileReader<User>(new File("file/users.avro"), userDatumReader);
User user = null;
while (dataFileReader.hasNext()) {
user = dataFileReader.next(user);
System.out.println(user);
}
}

根据我们上述生成的序列化file/users.avro文件反序列化生成的User实例,可以看到如下的输出:

{"name": "Alyssa", "favorite_number": , "favorite_color": null}
{"name": "Ben", "favorite_number": , "favorite_color": "red"}
{"name": "Charlie", "favorite_number": null, "favorite_color": "blue"}

二、不需要生成User类的方式

Avro中的数据始终与其相应的模式一起存储,这意味着无论我们是否提前知道模式,我们总是可以读取序列化项目。这允许我们在不生成代码的情况下执行序列化和反序列化。如果是这种方式的话,pom.xml里面的arvo插件不是必须的。

一、序列化User类

public static void serializing() throws IOException {
Schema schema = new Schema.Parser().parse(WithoutUserGen.class.getResourceAsStream("/user.avsc"));
GenericRecord user1 = new GenericData.Record(schema);
user1.put("name", "Alyssa");
user1.put("favorite_number", 256);
// Leave favorite color null GenericRecord user2 = new GenericData.Record(schema);
user2.put("name", "Ben");
user2.put("favorite_number", 7);
user2.put("favorite_color", "red"); File file = new File("file/users2.avro");
DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter);
dataFileWriter.create(schema, file);
dataFileWriter.append(user1);
dataFileWriter.append(user2);
dataFileWriter.close();
}

这里把两个User类的实例序列化到file/users2.avro文件中

二、反序列化User类

public static void deserializing() throws IOException {
Schema schema = new Schema.Parser().parse(WithoutUserGen.class.getResourceAsStream("/user.avsc"));
File file = new File("file/users2.avro");
DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(schema);
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(file, datumReader);
GenericRecord user = null;
while (dataFileReader.hasNext()) {
user = dataFileReader.next(user);
System.out.println(user);
}
}

可以看到以下的输出

{"name": "Alyssa", "favorite_number": , "favorite_color": null}
{"name": "Ben", "favorite_number": , "favorite_color": "red"}

友情链接

java基础---->序列化框架arvo的使用的更多相关文章

  1. Java基础——集合框架

    Java的集合框架是Java中很重要的一环,Java平台提供了一个全新的集合框架.“集合框架”主要由一组用来操作对象的接口组成.不同接口描述一组不同数据类型.Java平台的完整集合框架如下图所示: 上 ...

  2. Java基础-序列化

    Java序列化是将一个对象编码成一个字节流,反序列化将字节流编码转换成一个对象. 序列化是Java中实现持久化存储的一种方法: 为数据传输提供了线路级对象表示法. Java的序列化机制是通过在运行时判 ...

  3. Java基础—序列化与反序列化(转载)

    转载自: Java序列化与反序列化 1.Java序列化与反序列化 Java序列化是指把Java对象转换为字节序列的过程:而Java反序列化是指把字节序列恢复为Java对象的过程. 2.为什么需要序列化 ...

  4. Java基础--序列化Serializable

    对Java对象序列化的目的是持久化对象或者为RMI(远程方法调用)传递参数和返回值. 下面是一个序列化对象写入文件的例子: ---------------------------- package u ...

  5. Java基础学习框架总结

    内容:Java基础知识全面复习 时间:2019.9.3-2019.9.26 代码:D:/ProgramFiles/IDEA/hello_sort 一.基础知识 learning1 case分支 Inp ...

  6. java基础之框架篇(1)

    框架基础反射:反射是Java开发的一类动态相关机制.因为本身Java语言并不是一款动态语言,如果我们想要得到程序动态的效果,因此便引入了反射机制这一概念. 问题:Java中创建实例化对象有哪些方式? ...

  7. 十七、Java基础---------集合框架之Map

    前两篇文章中介绍了Collection框架,今天来介绍一下Map集合,并用综合事例来演示. Map<K,V> Map<K,V>:Map存储的是键值对形式的元素,它的每一个元素, ...

  8. 十五、Java基础---------集合框架体系以及List

    在介绍集合之前先说一下数组,正如我们所知,数组是某一类型数据的集合,强调的是数据,而且必须单一:集合框架的不同之处在于存储的数据类型没有任何限制,既可以存储基本数据类型(会自动提升为相应的包装类)也可 ...

  9. Java基础——序列化

    Java的“对象序列化”能将一个实现了Serialiable接口(标记接口,没有任何方法)的对象转化为一组byte,这样日后要用到这个对象的时候,就能把这些byte数据恢复出来,并据此重新构建那个对象 ...

随机推荐

  1. 菜鸟nginx源代码剖析数据结构篇(八) 缓冲区链表ngx_chain_t

    菜鸟nginx源代码剖析数据结构篇(八) 缓冲区链表 ngx_chain_t Author:Echo Chen(陈斌) Email:chenb19870707@gmail.com Blog:Blog. ...

  2. C#调试心经

    我们在做程序开发时,难免会遇到错误异常.如何快速地找到出错的地方.分析错误的原因以及找到解决问题的方案,是许多初级程序员困扰的问题,这也正是经验的宝贵之处.下面我将简单介绍在Visual Studio ...

  3. Shell脚本编程基础笔记二

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/8177697.html 一:输入 1:运行时参数 可以在启动脚本时,在其后输入参数. ./脚本 参数1 参数2. ...

  4. Python操作redis系列之 列表(list) (五)

    # -*- coding: utf- -*- import redis r =redis.Redis(host=,password=") 1. Lpush 命令将一个或多个值插入到列表头部. ...

  5. list与Set、Map区别及适用场景

    1.List,Set都是继承自Collection接口,Map则不是 2.List特点: 元素有放入顺序,元素可重复 ,Set特点:元素无放入顺序,元素不可重复,重复元素会覆盖掉,(注意:元素虽然无放 ...

  6. <转>详解C++的模板中typename关键字的用法

    用处1, 用在模板定义里, 标明其后的模板参数是类型参数. 例如: template<typename T, typename Y> T foo(const T& t, const ...

  7. 百度「Web 前端研发部」面试过程和常见问题 可能会采用哪些方法来面试 STAR 面试法 喜欢什么样的面试者 喜欢问的问题

    http://segmentfault.com/a/1190000002498800 在他们的github上看到的,收藏一下备用.看完觉得还有很多要努力的地方. FEX 的面试过程 我们一般会有 3 ...

  8. C#反射实现

    一.反射概念: 1.概念: 反射,通俗的讲就是我们在只知道一个对象的外部而不了解内部结构的情况下,通过反射这个技术可以使我们明确这个对象的内部实现. 在.NET中,反射是重要的机制,它可以动态的分析程 ...

  9. 【iCore4 双核心板_FPGA】例程十三:基于SPI的ARM与FPGA通信实验

    实验现象: 1.先烧写ARM程序,然后烧写FPGA程序. 2.打开串口精灵,通过串口精灵给ARM发送数据从而给FPGA发送数据 ,会接收到字符HELLO. 3.通过串口精灵发送命令可以控制ARM·LE ...

  10. 法线从object space到eye space的转换((normal matrix)

    对于顶点来说,从object Space转换到eye space, 使用model-view矩阵就好了.那么顶点的法线是否也可以直接使用model-view矩阵转化? 通常情况下是不行的. 如下两张图 ...