Debian Codegraph @

doc/content/en/docs/++version++/Getting started (Java)/_index.md

raw
1 ---
2 categories: []
3 tags: ["java"]
4 title: "Getting Started (Java)"
5 linkTitle: "Getting Started (Java)"
6 weight: 2
7 aliases:
8 - /docs/current/getting-started-java/
9 ---
10
11 <!--
12
13 Licensed to the Apache Software Foundation (ASF) under one
14 or more contributor license agreements. See the NOTICE file
15 distributed with this work for additional information
16 regarding copyright ownership. The ASF licenses this file
17 to you under the Apache License, Version 2.0 (the
18 "License"); you may not use this file except in compliance
19 with the License. You may obtain a copy of the License at
20
21 https://www.apache.org/licenses/LICENSE-2.0
22
23 Unless required by applicable law or agreed to in writing,
24 software distributed under the License is distributed on an
25 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
26 KIND, either express or implied. See the License for the
27 specific language governing permissions and limitations
28 under the License.
29
30 -->
31
32 This is a short guide for getting started with Apache Avro™ using Java. This guide only covers using Avro for data serialization; see Patrick Hunt's [Avro RPC Quick Start](https://github.com/phunt/avro-rpc-quickstart) for a good introduction to using Avro for RPC.
33
34 ## Download
35
36 Avro implementations for C, C++, C#, Java, PHP, Python, and Ruby can be downloaded from the [Apache Avro™ Download]({{< relref "/project/download" >}}) page. This guide uses Avro {{< avro_version >}}, the latest version at the time of writing. For the examples in this guide, download avro-{{< avro_version >}}.jar and avro-tools-{{< avro_version >}}.jar.
37
38 Alternatively, if you are using Maven, add the following dependency to your POM:
39
40 ```xml
41 <dependency>
42 <groupId>org.apache.avro</groupId>
43 <artifactId>avro</artifactId>
44 <version>{{< avro_version >}}</version>
45 </dependency>
46 ```
47
48 As well as the Avro Maven plugin (for performing code generation):
49
50 ```xml
51 <plugin>
52 <groupId>org.apache.avro</groupId>
53 <artifactId>avro-maven-plugin</artifactId>
54 <version>{{< avro_version >}}</version>
55 <configuration>
56 <sourceDirectory>${project.basedir}/src/main/avro/</sourceDirectory>
57 <outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
58 </configuration>
59 <executions>
60 <execution>
61 <phase>generate-sources</phase>
62 <goals>
63 <goal>schema</goal>
64 </goals>
65 </execution>
66 </executions>
67 </plugin>
68 <plugin>
69 <groupId>org.apache.maven.plugins</groupId>
70 <artifactId>maven-compiler-plugin</artifactId>
71 <configuration>
72 <source>1.8</source>
73 <target>1.8</target>
74 </configuration>
75 </plugin>
76 ```
77
78 You may also build the required Avro jars from source. Building Avro is beyond the scope of this guide; see the Build Documentation page in the wiki for more information.
79
80 ## Defining a schema
81
82 Avro schemas are defined using JSON or IDL (the latter requires an extra dependency). Schemas are composed of primitive types (null, boolean, int, long, float, double, bytes, and string) and complex types (record, enum, array, map, union, and fixed). You can learn more about Avro schemas and types from the specification, but for now let's start with a simple schema example, user.avsc:
83
84 ```json
85 {"namespace": "example.avro",
86 "type": "record",
87 "name": "User",
88 "fields": [
89 {"name": "name", "type": "string"},
90 {"name": "favorite_number", "type": ["int", "null"]},
91 {"name": "favorite_color", "type": ["string", "null"]}
92 ]
93 }
94 ```
95
96 This schema defines a record representing a hypothetical user. (Note that a schema file can only contain a single schema definition.) At minimum, a record definition must include its type ("type": "record"), a name ("name": "User"), and fields, in this case name, favorite_number, and favorite_color. We also define a namespace ("namespace": "example.avro"), which together with the name attribute defines the "full name" of the schema (example.avro.User in this case).
97
98 Fields are defined via an array of objects, each of which defines a name and type (other attributes are optional, see the record specification for more details). The type attribute of a field is another schema object, which can be either a primitive or complex type. For example, the name field of our User schema is the primitive type string, whereas the favorite_number and favorite_color fields are both unions, represented by JSON arrays. unions are a complex type that can be any of the types listed in the array; e.g., favorite_number can either be an int or null, essentially making it an optional field.
99
100 ## Serializing and deserializing with code generation
101
102 ### Compiling the schema
103 Code generation allows us to automatically create classes based on our previously-defined schema. Once we have defined the relevant classes, there is no need to use the schema directly in our programs. We use the avro-tools jar to generate code as follows:
104
105 ```shell
106 java -jar /path/to/avro-tools-{{< avro_version >}}.jar compile schema <schema file> <destination>
107 ```
108
109 This will generate the appropriate source files in a package based on the schema's namespace in the provided destination folder. For instance, to generate a User class in package example.avro from the schema defined above, run
110
111 ```shell
112 java -jar /path/to/avro-tools-{{< avro_version >}}.jar compile schema user.avsc .
113 ```
114
115 Note that if you using the Avro Maven plugin, there is no need to manually invoke the schema compiler; the plugin automatically performs code generation on any .avsc files present in the configured source directory.
116
117 ### Creating Users
118 Now that we've completed the code generation, let's create some Users, serialize them to a data file on disk, and then read back the file and deserialize the User objects.
119
120 First let's create some Users and set their fields.
121
122 ```java
123 User user1 = new User();
124 user1.setName("Alyssa");
125 user1.setFavoriteNumber(256);
126 // Leave favorite color null
127
128 // Alternate constructor
129 User user2 = new User("Ben", 7, "red");
130
131 // Construct via builder
132 User user3 = User.newBuilder()
133 .setName("Charlie")
134 .setFavoriteColor("blue")
135 .setFavoriteNumber(null)
136 .build();
137 ```
138
139 As shown in this example, Avro objects can be created either by invoking a constructor directly or by using a builder. Unlike constructors, builders will automatically set any default values specified in the schema. Additionally, builders validate the data as it set, whereas objects constructed directly will not cause an error until the object is serialized. However, using constructors directly generally offers better performance, as builders create a copy of the datastructure before it is written.
140
141 Note that we do not set user1's favorite color. Since that record is of type ["string", "null"], we can either set it to a string or leave it null; it is essentially optional. Similarly, we set user3's favorite number to null (using a builder requires setting all fields, even if they are null).
142
143 ### Serializing
144 Now let's serialize our Users to disk.
145
146 ```java
147 // Serialize user1, user2 and user3 to disk
148 DatumWriter<User> userDatumWriter = new SpecificDatumWriter<User>(User.class);
149 DataFileWriter<User> dataFileWriter = new DataFileWriter<User>(userDatumWriter);
150 dataFileWriter.create(user1.getSchema(), new File("users.avro"));
151 dataFileWriter.append(user1);
152 dataFileWriter.append(user2);
153 dataFileWriter.append(user3);
154 dataFileWriter.close();
155 ```
156
157 We create a DatumWriter, which converts Java objects into an in-memory serialized format. The SpecificDatumWriter class is used with generated classes and extracts the schema from the specified generated type.
158
159 Next we create a DataFileWriter, which writes the serialized records, as well as the schema, to the file specified in the dataFileWriter.create call. We write our users to the file via calls to the dataFileWriter.append method. When we are done writing, we close the data file.
160
161 ### Deserializing
162 Finally, let's deserialize the data file we just created.
163
164 ```java
165 // Deserialize Users from disk
166 DatumReader<User> userDatumReader = new SpecificDatumReader<User>(User.class);
167 DataFileReader<User> dataFileReader = new DataFileReader<User>(file, userDatumReader);
168 User user = null;
169 while (dataFileReader.hasNext()) {
170 // Reuse user object by passing it to next(). This saves us from
171 // allocating and garbage collecting many objects for files with
172 // many items.
173 user = dataFileReader.next(user);
174 System.out.println(user);
175 }
176 ```
177
178 This snippet will output:
179
180 ```json
181 {"name": "Alyssa", "favorite_number": 256, "favorite_color": null}
182 {"name": "Ben", "favorite_number": 7, "favorite_color": "red"}
183 {"name": "Charlie", "favorite_number": null, "favorite_color": "blue"}
184 ```
185
186 Deserializing is very similar to serializing. We create a SpecificDatumReader, analogous to the SpecificDatumWriter we used in serialization, which converts in-memory serialized items into instances of our generated class, in this case User. We pass the DatumReader and the previously created File to a DataFileReader, analogous to the DataFileWriter, which reads both the schema used by the writer as well as the data from the file on disk. The data will be read using the writer's schema included in the file and the schema provided by the reader, in this case the User class. The writer's schema is needed to know the order in which fields were written, while the reader's schema is needed to know what fields are expected and how to fill in default values for fields added since the file was written. If there are differences between the two schemas, they are resolved according to the Schema Resolution specification.
187
188 Next we use the DataFileReader to iterate through the serialized Users and print the deserialized object to stdout. Note how we perform the iteration: we create a single User object which we store the current deserialized user in, and pass this record object to every call of dataFileReader.next. This is a performance optimization that allows the DataFileReader to reuse the same User object rather than allocating a new User for every iteration, which can be very expensive in terms of object allocation and garbage collection if we deserialize a large data file. While this technique is the standard way to iterate through a data file, it's also possible to use for (User user : dataFileReader) if performance is not a concern.
189
190 ### Compiling and running the example code
191 This example code is included as a Maven project in the examples/java-example directory in the Avro docs. From this directory, execute the following commands to build and run the example:
192
193 ```shell
194 $ mvn compile # includes code generation via Avro Maven plugin
195 $ mvn -q exec:java -Dexec.mainClass=example.SpecificMain
196 ```
197
198 ### Beta feature: Generating faster code
199 In release 1.9.0, we introduced a new approach to generating code that speeds up decoding of objects by more than 10% and encoding by more than 30% (future performance enhancements are underway). To ensure a smooth introduction of this change into production systems, this feature is controlled by a feature flag, the system property org.apache.avro.specific.use_custom_coders. In this first release, this feature is off by default. To turn it on, set the system flag to true at runtime. In the sample above, for example, you could enable the fater coders as follows:
200
201 $ mvn -q exec:java -Dexec.mainClass=example.SpecificMain \
202 -Dorg.apache.avro.specific.use_custom_coders=true
203
204 Note that you do not have to recompile your Avro schema to have access to this feature. The feature is compiled and built into your code, and you turn it on and off at runtime using the feature flag. As a result, you can turn it on during testing, for example, and then off in production. Or you can turn it on in production, and quickly turn it off if something breaks.
205
206 We encourage the Avro community to exercise this new feature early to help build confidence. (For those paying one-demand for compute resources in the cloud, it can lead to meaningful cost savings.) As confidence builds, we will turn this feature on by default, and eventually eliminate the feature flag (and the old code).
207
208 ## Serializing and deserializing without code generation
209 Data in Avro is always stored with its corresponding schema, meaning we can always read a serialized item regardless of whether we know the schema ahead of time. This allows us to perform serialization and deserialization without code generation.
210
211 Let's go over the same example as in the previous section, but without using code generation: we'll create some users, serialize them to a data file on disk, and then read back the file and deserialize the users objects.
212
213 ### Creating users
214 First, we use a SchemaParser to read our schema definition and create a Schema object.
215
216 ```java
217 Schema schema = new SchemaParser().parse(new File("user.avsc")).mainSchema();
218 ```
219
220 Using this schema, let's create some users.
221
222 ```java
223 GenericRecord user1 = new GenericData.Record(schema);
224 user1.put("name", "Alyssa");
225 user1.put("favorite_number", 256);
226 // Leave favorite color null
227
228 GenericRecord user2 = new GenericData.Record(schema);
229 user2.put("name", "Ben");
230 user2.put("favorite_number", 7);
231 user2.put("favorite_color", "red");
232 ```
233
234 Since we're not using code generation, we use GenericRecords to represent users. GenericRecord uses the schema to verify that we only specify valid fields. If we try to set a non-existent field (e.g., user1.put("favorite_animal", "cat")), we'll get an AvroRuntimeException when we run the program.
235
236 Note that we do not set user1's favorite color. Since that record is of type ["string", "null"], we can either set it to a string or leave it null; it is essentially optional.
237
238 ### Serializing
239 Now that we've created our user objects, serializing and deserializing them is almost identical to the example above which uses code generation. The main difference is that we use generic instead of specific readers and writers.
240
241 First we'll serialize our users to a data file on disk.
242
243 ```java
244 // Serialize user1 and user2 to disk
245 File file = new File("users.avro");
246 DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
247 DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
248 dataFileWriter.create(schema, file);
249 dataFileWriter.append(user1);
250 dataFileWriter.append(user2);
251 dataFileWriter.close();
252 ```
253
254 We create a DatumWriter, which converts Java objects into an in-memory serialized format. Since we are not using code generation, we create a GenericDatumWriter. It requires the schema both to determine how to write the GenericRecords and to verify that all non-nullable fields are present.
255
256 As in the code generation example, we also create a DataFileWriter, which writes the serialized records, as well as the schema, to the file specified in the dataFileWriter.create call. We write our users to the file via calls to the dataFileWriter.append method. When we are done writing, we close the data file.
257
258 ### Deserializing
259 Finally, we'll deserialize the data file we just created.
260
261 ```java
262 // Deserialize users from disk
263 DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);
264 DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader);
265 GenericRecord user = null;
266 while (dataFileReader.hasNext()) {
267 // Reuse user object by passing it to next(). This saves us from
268 // allocating and garbage collecting many objects for files with
269 // many items.
270 user = dataFileReader.next(user);
271 System.out.println(user);
272 ```
273
274 This outputs:
275
276 ```json
277 {"name": "Alyssa", "favorite_number": 256, "favorite_color": null}
278 {"name": "Ben", "favorite_number": 7, "favorite_color": "red"}
279 ```
280
281 Deserializing is very similar to serializing. We create a GenericDatumReader, analogous to the GenericDatumWriter we used in serialization, which converts in-memory serialized items into GenericRecords. We pass the DatumReader and the previously created File to a DataFileReader, analogous to the DataFileWriter, which reads both the schema used by the writer as well as the data from the file on disk. The data will be read using the writer's schema included in the file, and the reader's schema provided to the GenericDatumReader. The writer's schema is needed to know the order in which fields were written, while the reader's schema is needed to know what fields are expected and how to fill in default values for fields added since the file was written. If there are differences between the two schemas, they are resolved according to the Schema Resolution specification.
282
283 Next, we use the DataFileReader to iterate through the serialized users and print the deserialized object to stdout. Note how we perform the iteration: we create a single GenericRecord object which we store the current deserialized user in, and pass this record object to every call of dataFileReader.next. This is a performance optimization that allows the DataFileReader to reuse the same record object rather than allocating a new GenericRecord for every iteration, which can be very expensive in terms of object allocation and garbage collection if we deserialize a large data file. While this technique is the standard way to iterate through a data file, it's also possible to use for (GenericRecord user : dataFileReader) if performance is not a concern.
284
285 ### Compiling and running the example code
286 This example code is included as a Maven project in the examples/java-example directory in the Avro docs. From this directory, execute the following commands to build and run the example:
287
288 ```shell
289 $ mvn compile
290 $ mvn -q exec:java -Dexec.mainClass=example.GenericMain
291 ```