本文示例来源于https://github.com/phunt/avro-rpc-quickstart
1)定义avro protocol, 可以先写IDL文件,然后转换为protocol文件*.avpr,也可以直接写avpr,例如:
{"namespace": "example.proto",
"protocol": "Mail",
"types": [
{"name": "Message", "type": "record",
"fields": [
{"name": "to", "type": "string"},
{"name": "from", "type": "string"},
{"name": "body", "type": "string"}
]
}
],
"messages": {
"send": {
"request": [{"name": "message", "type": "Message"}],
"response": "string"
}
}
}
2) 编译生成协议类以及消息类,maven插件可以自动完成协议Mail类以及消息Message类
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>${avro.version}</version>
<executions>
<execution>
<id>schemas</id>
<phase>generate-sources</phase>
<goals>
<goal>schema</goal>
<goal>protocol</goal>
<goal>idl-protocol</goal>
</goals>
</execution>
</executions>
</plugin>
3) 程序中通过调用avro的IPC接口实现客户端服务器通信,例如:
server = new NettyServer(new SpecificResponder(Mail.class, new MailImpl()), new InetSocketAddress(65111));
NettyTransceiver client = new NettyTransceiver(new InetSocketAddress(65111));
// client code - attach to the server and send a message
Mail proxy = (Mail) SpecificRequestor.getClient(Mail.class, client);
System.out.println("Client built, got proxy");
// fill in the Message record and send it
Message message = new Message();
message.setTo(new Utf8(args[0]));
message.setFrom(new Utf8(args[1]));
message.setBody(new Utf8(args[2]));
System.out.println("Calling proxy.send with message: " + message.toString());
System.out.println("Result: " + proxy.send(message));
源码:http://download.csdn.net/detail/sundongsdu/8920035
参考文献:
http://avro.apache.org/docs/current/idl.html