本文的目的主要是总结下基于Avro Schema代码生成,然后进行序列化和反序列化开发的基本流程。需要指出的是,Avro并不要求一定得根据Schema文件生成代码,这对于动态类型语言很有用。
1. 添加Maven依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>learn</groupId> <artifactId>learn.avro</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!--avro core--> <dependency> <groupId>org.apache.avro</groupId> <artifactId>avro</artifactId> <version>1.7.7</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.avro</groupId> <artifactId>avro-maven-plugin</artifactId> <version>1.7.7</version> <executions> <execution> <phase>generate-sources</phase> <goals> <!--Maven goal that helps for code generation--> <goal>schema</goal> <goal>protocol</goal> <goal>idl-protocol</goal> </goals> <configuration> <!--sourceDirectory: where to find the schema file, schema: .avsc; protocol: .avpr--> <sourceDirectory>${project.basedir}/src/main/avro/</sourceDirectory> <outputDirectory>${project.basedir}/src/main/java/</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>
2.定义schema文件(users.avsc)
放置到src/main/avro目录下
{"namespace": "examples.avro.simple", "type": "record", "name": "User", "fields": [ {"name": "name", "type": "string"}, {"name": "favorite_number", "type": ["int", "null"]}, {"name": "favorite_color", "type": ["string", "null"]} ] }
namespace:包名
type: record表示记录,可以理解为几个field构成的一个record,类似于Java的JavaBean
name:类名
fiels:成员变量,favorite_number最后会解释成getFavoriteNumber和setFavoriteNumber
3. 生成User类
在Intellij Idea的Maven视图中,learn avro->Plugins->avro->avro:schema,右击avro:schema,执行Run Maven Build,生成schema对应的Java实体类
/** * Autogenerated by Avro * * DO NOT EDIT DIRECTLY */ package examples.avro.simple; @SuppressWarnings("all") @org.apache.avro.specific.AvroGenerated public class User extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord { public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"User\",\"namespace\":\"example.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$; } @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. */ 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. */ 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. */ 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. */ 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 */ public static User.Builder newBuilder() { return new User.Builder(); } /** Creates a new User RecordBuilder by copying an existing Builder */ public static User.Builder newBuilder(User.Builder other) { return new User.Builder(other); } /** Creates a new User RecordBuilder by copying an existing User instance */ public static User.Builder newBuilder(User other) { return new 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(User.SCHEMA$); } /** Creates a Builder by copying an existing Builder */ private Builder(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 */ private Builder(User other) { super(User.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 */ public java.lang.CharSequence getName() { return name; } /** Sets the value of the 'name' field */ public 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 */ public boolean hasName() { return fieldSetFlags()[0]; } /** Clears the value of the 'name' field */ public User.Builder clearName() { name = null; fieldSetFlags()[0] = false; return this; } /** Gets the value of the 'favorite_number' field */ public java.lang.Integer getFavoriteNumber() { return favorite_number; } /** Sets the value of the 'favorite_number' field */ public 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 */ public boolean hasFavoriteNumber() { return fieldSetFlags()[1]; } /** Clears the value of the 'favorite_number' field */ public User.Builder clearFavoriteNumber() { favorite_number = null; fieldSetFlags()[1] = false; return this; } /** Gets the value of the 'favorite_color' field */ public java.lang.CharSequence getFavoriteColor() { return favorite_color; } /** Sets the value of the 'favorite_color' field */ public 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 */ public boolean hasFavoriteColor() { return fieldSetFlags()[2]; } /** Clears the value of the 'favorite_color' field */ public User.Builder clearFavoriteColor() { favorite_color = null; fieldSetFlags()[2] = false; return this; } @Override 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 (Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } }
4. User类序列化和反序列化测试
package examples.avro.simple; import java.io.File; import java.io.Serializable; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileWriter; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumWriter; public class UserTest { public static void main(String[] args) throws Exception { ///无参构造函数,依赖设值注入 User user1 = new User(); user1.setName("Alyssa"); user1.setFavoriteNumber(256); //user1没有对favorite color赋值 ///注意:User并没有实现Java的Serializable接口 System.out.println(user1 instanceof Serializable); ///重载的构造方法 User user2 = new User("Ben", 7, "red"); //使用builder构建对象 User user3 = User.newBuilder() .setName("Charlie") .setFavoriteColor("blue") .setFavoriteNumber(null) .build(); System.out.println(user3.getName() + "," + user3.getFavoriteColor()); ///1. 序列化包含Schema和3个User对象到c:/users.avro文件 DatumWriter<User> userDatumWriter = new SpecificDatumWriter<User>(User.class); DataFileWriter<User> dataFileWriter = new DataFileWriter<User>(userDatumWriter); dataFileWriter.create(user1.getSchema(), new File("c:/users.avro")); dataFileWriter.append(user1); dataFileWriter.append(user2); dataFileWriter.append(user3); dataFileWriter.close(); ///2. 从c:/users.avro文件反序列化对象 DatumReader<User> userDatumReader = new SpecificDatumReader<User>(User.class); DataFileReader<User> dataFileReader = new DataFileReader<User>(new File("c:/users.avro"), userDatumReader); User user = null; while (dataFileReader.hasNext()) { // Reuse user object by passing it to next(). This saves us from // allocating and garbage collecting many objects for files with // many items. user = dataFileReader.next(user); System.out.println(user); ///输出JSON格式的数据,Avro对User类的toString进行了改写 } } }
相关推荐
神奇宝贝(PokemonGo)基于Jetpack+MVVM+Repository设计模式+Data
用于试用 Dev Containers 的 Python 示例项目试用开发容器Python开发容器是一个具有明确定义的工具/运行时堆栈及其先决条件的运行容器。您可以使用GitHub Codespaces或Visual Studio Code Dev Containers试用开发容器。这是一个示例项目,您可以通过几个简单的步骤尝试任一选项。我们还有各种其他vscode-remote-try-*示例项目。注意如果您已经有代码空间或开发容器,则可以跳至“要尝试的事情”部分。设置开发容器GitHub Codespaces请按照以下步骤在 Codespace 中打开此示例单击代码下拉菜单。单击Codespaces选项卡。单击主屏幕上的“创建代码空间”。有关创建代码空间的更多信息,请访问GitHub 文档。VS Code 开发容器如果您已安装 VS Code 和 Docker,则可以单击上方或此处的徽章开始使用。单击这些链接将导致 VS Code 根据需要自动安装 Dev Containers 扩展,将源代码克隆到容器卷中,并启动开发容器以供使用。按
springboot vue3前后端分离
数学建模-神经网络算法 lecture 11 线性随机系统辨识示例 共9页.pptx
优质粳稻生产技术规程.docx
算法 - Python 目录灵感与动力贡献指南从这里开始所有算法均用 Python 3 实现(用于教育)这些实现仅用于学习目的。如果您想贡献更有效的解决方案,请随时打开问题并提交您的解决方案。灵感你可以在LeetCode 算法中寻找要实现的算法若要贡献,请确保算法尚未提交!请确保在您的 PR 中添加问题编号。贡献指南文件夹和文件请确保你的文件位于 -Folder 中LeetCode,并且命名如下 0001_TwoSum.py-> LeetCode 问题的 4 位数字、下划线、LeetCodeName开放问题当您打开问题时,请确保问题尚未实现(查看代码/Leetcode 以获取问题编号)。现有问题打开的问题将被关闭,并且对此问题的 PR 被标记为垃圾邮件 。打开问题的贡献者将被优先分配到该问题。如果大约 7 天内没有 PR,则问题将分配给另一个贡献者。拉取请求只有与问题相结合并符合命名约定(参见文件夹和文件)的 Pull 请求才会被合并!如果 PR 中没有加入问题,您的 PR 将被标记为垃圾邮件并关闭。如果您的代码未通
用于接收和交互来自 Slack 的 RTM API 的事件的框架python-rtmbot此项目不再处于积极开发阶段。如果您刚刚开始,我们建议您先查看Python SDK。如果您一直在使用此项目,我们只会解决关键问题(例如安全问题),但我们建议您计划迁移到 Python SDK。您仍然可以提交问题并向我们寻求帮助! 如果您有兴趣在未来维护此软件包,请联系我们 一个用 Python 编写的 Slack 机器人,通过 RTM API 连接。Python-rtmbot 是一个机器人引擎。任何了解Slack API和 Python的人都应该熟悉插件架构。配置文件格式为 YAML。该项目目前处于 1.0 之前的版本。因此,您应该计划不时进行重大更改。对于任何重大更改,我们将在 1.0 之前的版本中调整次要版本。(例如 0.2.4 -> 0.3.0 意味着重大更改)。如果稳定性很重要,您可能希望锁定特定的次要版本)与 webhook 的一些区别不需要网络服务器来接收消息可以回复用户的直接消息以 Slack 用户(或机器人)身份登录机器人用户必须被邀请加入频道
基于django的音乐推荐系统.zip
北京理工大学<Python机器学习应用>超详细学习笔记和代码注释(未完待续)
kernel-5.15-rc7.zip
神经网络-DenseNet网络结构
rbac组件(基于角色的权限控制)
C++ Vigenère 密码(解密代码)
数学建模培训资料 数学建模实战题目真题答案解析解题过程&论文报告 杭州消防设置-对杭州市消防局设置的研究 共8页.pdf
老年用品产品推广目录分类表.docx
本项目是基于Python的期货程序化交易系统的设计与实现,旨在为计算机相关专业学生提供一个实践性强、贴近实际应用场景的项目案例。通过这一项目,学生们能够深入了解程序化交易的基本原理和实现方法,同时锻炼自身的编程技能、数据分析能力以及金融市场的洞察力。 项目的主要功能包括:自动收集和处理市场数据、基于预设策略进行交易决策、实时执行交易指令、监控交易风险以及生成详细的交易报告。系统采用模块化设计,主要包括数据采集模块、策略执行模块、交易执行模块和风险管理模块,各个模块之间通过明确的接口进行交互。项目采用的编程语言为Python,利用其强大的数据处理库和机器学习库,保证了系统的灵活性和扩展性。开发这一项目的目的是让学生们在实践中学习和掌握程序化交易的核心技术,提升其在金融科技领域的就业竞争力。
基于java的校园失物招领平台设计与实现.docx
Javascript Ninja 课程JavaScript Ninja 课程Inscreva-se agora mesmo e ganhe 10% de desconto!Como tirar dúvidas sobre 或 conteúdo do curso访问问题页面Pesquise nas发出abertas e fechadas, se a mesma dúvida já foi postadaSe não foi, crie uma nova issues , coloque um titulo que tenha a ver com a sua dúvida, e descreva-a com o maior nível detalhes possíveis, para que possamos te ajudar:)摘要Veja o sumário completo do curso aqui。赞同!:D
solid.python通过示例在 Python 中解释SOLID 原则。单一职责原则开放/封闭原则里氏替换原则接口隔离原则依赖倒置原则
公交信息在线查询系统 微信小程序+SSM毕业设计 源码+数据库+论文+启动教程 项目启动教程:https://www.bilibili.com/video/BV1BfB2YYEnS