第 19 章 Avro 组件
作为 Camel 2.10 版本提供
此组件为 avro 提供了一个数据格式,允许使用 Apache Avro 的二进制数据格式对消息进行序列化和反序列化。此外,它还通过提供生产者和消费者端点(通过 netty 或 http),为 Apache Avro 的 rpc 提供支持。
Maven 用户需要将以下依赖项添加到其 pom.xml
中:
<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-avro</artifactId> <version>x.x.x</version> <!-- use the same version as your Camel core version --> </dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-avro</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency>
19.1. Apache Avro 概述
Avro 允许您使用 json 等格式定义消息类型和协议,然后为指定类型和消息生成 java 代码。下面是一个 schema 的示例。
{"namespace": "org.apache.camel.avro.generated", "protocol": "KeyValueProtocol", "types": [ {"name": "Key", "type": "record", "fields": [ {"name": "key", "type": "string"} ] }, {"name": "Value", "type": "record", "fields": [ {"name": "value", "type": "string"} ] } ], "messages": { "put": { "request": [{"name": "key", "type": "Key"}, {"name": "value", "type": "Value"} ], "response": "null" }, "get": { "request": [{"name": "key", "type": "Key"}], "response": "Value" } } }
{"namespace": "org.apache.camel.avro.generated",
"protocol": "KeyValueProtocol",
"types": [
{"name": "Key", "type": "record",
"fields": [
{"name": "key", "type": "string"}
]
},
{"name": "Value", "type": "record",
"fields": [
{"name": "value", "type": "string"}
]
}
],
"messages": {
"put": {
"request": [{"name": "key", "type": "Key"}, {"name": "value", "type": "Value"} ],
"response": "null"
},
"get": {
"request": [{"name": "key", "type": "Key"}],
"response": "Value"
}
}
}
您可以使用 maven、at 等模式轻松生成类。有关详细信息,请参阅 Apache Avro 文档。
但是,它不强制采用一种模式,而且您可以为现有类创建 schema。自 2.12 开始,您可以使用现有协议接口发出 RCP 调用。您应该为协议本身使用接口,POJO Bean 或原语/字符串类用于参数和结果类型。下面是与上述 schema 对应的类示例:
package org.apache.camel.avro.reflection; public interface KeyValueProtocol { void put(String key, Value value); Value get(String key); } class Value { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
package org.apache.camel.avro.reflection;
public interface KeyValueProtocol {
void put(String key, Value value);
Value get(String key);
}
class Value {
private String value;
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
}
注:现有类只能用于 RPC (请参阅以下),而不是数据格式。