Avro「建议收藏」

Avro「建议收藏」序列化/反序列化机制将对象转化为字节来进行存储称之为序列化;将字节还原会对象的过程称之为反序列化java中的序列化反序列化机制:需要利用原生流来实现,Serializable(该对象可以进行序列化/反序列化),static/transient(被修饰之后不能序列化/反序列化),serialVersionUID(版本号,如果版本号对上了再进行序列化/反序列,如果对不上,不进行序列化/反序列化…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

序列化/反序列化机制

将对象转化为字节来进行存储称之为序列化;将字节还原会对象的过程称之为反序列化

java中的序列化反序列化机制:需要利用原生流来实现,Serializable(该对象可以进行序列化/反序列化),static/transient(被修饰之后不能序列化/反序列化),serialVersionUID(版本号,如果版本号对上了再进行序列化/反序列,如果对不上,不进行序列化/反序列化)
原生机制缺点:

  1. 效率低
  2. 占用空间比较大:将类以及对象中的信息全部输出
  3. 兼容性较差:只能支持java使用

Avro-大数据通用的序列化器

简介

Apache Avro(以下简称 Avro)是一种与编程语言无关的序列化格式。Doug Cutting 创建了这个项目,目的是提供一种共享数据文件的方式。

Avro 数据通过与语言无关的 schema 来定义。schema 通过 JSON 来描述,数据被序列化成二进制文件或 JSON 文件,不过一般会使用二进制文件。Avro 在读写文件时需要用到 schema,schema 一般会被内嵌在数据文件里。

是Apache的开源项目。(天然支持Hadoop)
利用固定格式的文件(.avsc)来实现不同平台之间的解析操作。

Avro支持类型

Avro简单格式列表(8种)

原生类型 说明
null 表示没有值
boolean 表示一个二级制布尔值
int 表示32位有符号整数
long 表示64位有符号整数
float 表示32位单精度浮点数
double 表示64位双精度浮点数
bytes 表示8位无符号字节序列
string 表示字符序列

Avro复杂格式列表(6种)

复杂类型 属性 说明
Records type name record
name(必有属性) a JSON string
type (必有属性) a schema/a string of defined record
fields(必有属性) a JSON array, listing fields (required)
namespace a JSON string that qualifies the name(optional)
doc a JSON string providing documentation to the user of this schema (optional)
aliases a JSON array of strings, providing alternate names for this record (optional)
default a default value for field when lack
order ordering of this field.
Enum type name enum
name(必有属性) a JSON string
symbols(必有属性) a JSON array, listing symbols, as JSON strings (required). All symbols in an enum must be uniqu
namespace a JSON string that qualifies the name(optional)
doc a JSON string providing documentation to the user of this schema (optional)
aliases a JSON array of strings, providing alternate names for this record (optional)
Arrays type name array
items the schema of the array’s items
Maps type name map
values the schema of the map’s values( eg:{“type”: “map”, “values”: “long”} )
Fixed type name fixed
name(必有属性) a string naming this fixed (required)
namespace a JSON string that qualifies the name(optional)
aliases a JSON array of strings, providing alternate names for this record (optional)
size aan integer, specifying the number of bytes per value (required)

Test.avsc文件 所有格式实例

说明:Test.avsv文件,利用avro的插件可生成对应的Test类,这个类可以利用avro的API序列化/反序列化

{ 
   "namespace": "avro.domain", 
	"type": "record", 
	"name": "Test", 
	"fields": [   
		{ 
   "name": "stringVar", "type": "string"},   
		{ 
   "name": "bytesVar", "type": ["bytes", "null"]},  
		{ 
   "name": "booleanVar",  "type": "boolean"},   
		{ 
   "name": "intVar",  "type": "int", "order":"descending"},   	
		{ 
   "name": "longVar",  "type": ["long", "null"], "order":"ascending"},   
		{ 
   "name": "floatVar",  "type": "float"},   
		{ 
   "name": "doubleVar",  "type": "double"},   
		{ 
   "name": "enumVar",  "type": { 
   "type": "enum", "name": "Suit", "symbols" : ["SPADES ", "HEARTS", "DIAMONDS", "CLUBS"]}},   
		{ 
   "name": "strArrayVar", "type": { 
   "type": "array", "items": "string"}},   
		{ 
   "name": "intArrayVar", "type": { 
   "type": "array", "items": "int"}},     
		{ 
   "name": "mapVar", "type": { 
   "type": "map", "values": "long"}},   
		{ 
   "name": "fixedVar", "type": { 
   "type": "fixed", "size": 16, "name": "md5"}} 
	] 
}

Jetbrains全家桶1年46,售后保障稳定

利用AVRO定义avdl文件,生成类

avdl文件用于avro生成协议方法的。

实现步骤:

  1. 创建maven项目
  2. 添加pom依赖
<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--日志依赖-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>1.6.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <!-- avro的依赖 -->
      <groupId>org.apache.avro</groupId>
      <artifactId>avro</artifactId>
      <version>1.7.5</version>
    </dependency>
    <dependency>
      <groupId>org.apache.avro</groupId>
      <artifactId>avro-ipc</artifactId>
      <version>1.7.5</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
      </plugin>
      <plugin>
        <groupId>org.apache.avro</groupId>
        <artifactId>avro-maven-plugin</artifactId>
        <version>1.7.5</version>
        <executions>
          <execution>
            <id>schemas</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>schema</goal>
              <goal>protocol</goal>
              <goal>idl-protocol</goal>
            </goals>
            <configuration>
            	<!--存放avsc文件的地址-->
              <sourceDirectory>${ 
   project.basedir}/src/main/avro/</sourceDirectory>
              <!--生成源码的地址-->
              <outputDirectory>${ 
   project.basedir}/src/main/java/</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  1. 在src\main\avro目录下新建一个后缀为avsc的文件,比如User.avsc文件
    在这里插入图片描述
  2. 根据avro格式要求以及业务要求编辑这个文件(这里只做简单的示范)
{
	"namespace":"avro.pojo",
	"type":"record",
	"name":"User",
	"fields":
	[
		{"name":"name","type":"string"},
		{"name":"age","type":"int"}
	]
}
  1. 生成代码
    eclipse:(项目名右键)
    在这里插入图片描述idea:
    在这里插入图片描述就会在指定的目录下生成类:
    在这里插入图片描述
    这里生成的代码就不贴了,可以自己生成之后进行查看!

对实体类简单的调用

// User user = new User();
// user.setName("鲁智深");
// user.setAge(18);
// User user = new User("史进", 80);

// User user = User.newBuilder().setName("公孙胜").setAge(150).build();
// 利用原对象构建新对象
// 实际上底层是调用的clone方法来进行克隆
User user = User.newBuilder(new User("李逵", 80)).setAge(70).build();

System.out.println(user);

序列化

public void write() throws IOException { 
   

		User user = new User("Amy", 40);

		DatumWriter<User> dw = new SpecificDatumWriter<>(User.class);
		DataFileWriter<User> dfw = new DataFileWriter<>(dw);

		// 指定写出文件
		dfw.create(user.getSchema(), new File("1.txt"));

		dfw.append(user);
		dfw.append(new User("Sam", 70));
		dfw.append(new User("Bob", 70));

		dfw.close();
}

反序列化

public void read() throws IOException { 
   

		DatumReader<User> dr = new SpecificDatumReader<>(User.class);
		DataFileReader<User> dfr = new DataFileReader<>(new File("1.txt"), dr);

		// 提供了迭代机制来迭代读取数据
		// while(dfr.hasNext()){ 
   
		//
		// User user = dfr.next();
		// System.out.println(user);
		// }

		// Lambda表达式
		// dfr.forEach(u -> System.out.println(u));
		// 对象方法的传递
		dfr.forEach(System.out::println);

		dfr.close();
}

Avro天然支持RPC
Avro是基于Netty的

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/200766.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • python滑动验证码_python编程是啥

    python滑动验证码_python编程是啥程序功能:程序模仿登入京东主页,自动输入帐号和密码,完成滑块验证,最后领取每日签京豆关键难点:80%的难点在于滑块验证importtimeimportcv2importrandomimportopenpyxlfromurllibimportrequestfromseleniumimportwebdriverimportnumpyasnpfromselenium.webdriver.common.action_chainsimportActionChai

    2022年9月2日
    3
  • 解决Android SDK Manager下载太慢问题

    解决Android SDK Manager下载太慢问题1、打开androidsdkmanager2、打开tool->options,如图所示3、将ProxySettings里的HTTPProxyServer和HTTPProxyPort分别设置成mirrors.neusoft.edu.cn和80将Others中的Forcehttps://…sourcestobefetchedusinghttp://.

    2022年7月19日
    36
  • MFC之COleVariant类

    MFC之COleVariant类COleVariant本质上是一个枚举,用同一种类型来表达不同的子类型。如同boost中的variant。 COleVariant类是对VARIANT结构的封装。  VARIANT结构包含两部分。其一是VARTYPE型的成员变量vt;其二是个联合类型,这个联合包含了VC常用的几乎所有类型。因为联合用的是相同的存储空间,因此对联合的内容的解释依赖于vt。  例如,  若vt的…

    2022年7月18日
    10
  • siamfc++代码_siacoin

    siamfc++代码_siacoinSiamFC++:TowardsRobustandAccurateVisualTrackingwithTargetEstimationGuidelines摘要。视觉跟踪问题要求对给定目标进行高效的鲁棒分类和精确的状态估计。以往的方法提出了多种目标状态估计方法,但很少有方法考虑到视觉跟踪问题本身的特殊性。在仔细分析的基础上,为高性能通用目标跟踪器的设计提供了一套实用的目标状态估计指导原则。遵循这些指导原则,我们通过引入分类和目标状态估计分支(G1)、无模糊性分类评分(G2)、无先验知识跟

    2022年10月1日
    0
  • 数据结构:表达式求值

    数据结构:表达式求值数据结构:表达式求值表达式求值是程序设计语言编译的一个最基本问题,其中任何一个表达式都是由操作数、运算符(±*/)、界限符(#,(,),[,])组成。运算符和界限符统称算符。算符的优先级关系为(数学角度上):为了通过代码实现,我们定义两个工作栈,一个叫OPTR,存运算符和界限符;另一个存OPND,存操作数或运算结果。首先OPND为空栈,OPTR首先存’#’为栈底元素。依次读取算术表达式…

    2022年6月15日
    30
  • HDU 1541 Stars (树状数组)

    HDU 1541 Stars (树状数组)

    2022年1月10日
    32

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号