RPC_AVRO实例
发布时间: 2012-12-22 12:05:06 作者: rapoo
RPC_AVRO范例
1.下载与安装
官方网站:http://avro.apache.org/
下载地址:http://labs.renren.com/apache-mirror//avro/avro-1.5.1/avro-src-1.5.1.tar.gz
安装之前确保已经装了maven
其中定义了1种类型叫做message,有5个成员name、type、price、valid、content。还定义了1个消息服务叫做sendMessage,输入有一个参数,类型是message,返回message。
3.序列化
Avro有两种序列化编码:binary和JSON。
3.1.Binary Encoding
基本类型:
null:0字节
boolean:1个字节——0(false)或1(true)
int和long使用变长的zig-zag编码
float:4个字节
double:8个字节
bytes:1个long,后边跟着字节序列
string:1个long,后边跟着UTF-8编码的字符
3.2.records
按字段声明的顺序编码值,如下面一个record schema:
实例化这个record,a字段的值是27(编码为0×36),b字段的值是“foo”(编码为06 66 6f 6f),那么这个record编码结果是:
package avro;?import?java.net.URL;import?java.nio.ByteBuffer;import?java.util.Arrays;?import?org.apache.avro.util.Utf8;import?org.apache.avro.Protocol;import?org.apache.avro.generic.GenericData;import?org.apache.avro.generic.GenericRecord;import?org.apache.avro.ipc.HttpTransceiver;import?org.apache.avro.ipc.Transceiver;import?org.apache.avro.ipc.generic.GenericRequestor;?public?class Client {? ? private?Protocol protocol = null;? ? private?String host = null;? ? private?int port = 0;? ? private?int size = 0;? ? private?int count = 0;?? ? public?Client(Protocol protocol, String host, int port, int size, int count) {? ? ? ? this.protocol = protocol;? ? ? ? this.host = host;? ? ? ? this.port = port;? ? ? ? this.size = size;? ? ? ? this.count = count;? ? }?? ? public?long sendMessage() throws Exception {? ? ? ? GenericRecord?requestData = new GenericData.Record(? ? ? ? ? ? ? ? protocol.getType("message"));? ? ? ? // initiate the request data? ? ? ? …?? ? ? ? GenericRecord?request = new GenericData.Record(protocol.getMessages()? ? ? ? ? ? ? ? .get("sendMessage").getRequest());? ? ? ? request.put("message", requestData);?? ? ? ? Transceiver?t = new HttpTransceiver(new URL("http://" + host + ":"? ? ? ? ? ? ? ? + port));? ? ? ? GenericRequestor?requestor = new GenericRequestor(protocol, t);?? ? ? ? long?start = System.currentTimeMillis();? ? ? ? for?(int i = 0; i < count; i++) {? ? ? ? ? ? requestor.request("sendMessage", request);? ? ? ? }? ? ? ? long?end = System.currentTimeMillis();? ? ? ? System.out.println(end - start);? ? ? ? return?end - start;? ? }?? ? public?long run() {? ? ? ? long?res = 0;? ? ? ? try?{? ? ? ? ? ? res = sendMessage();? ? ? ? }?catch (Exception e) {? ? ? ? ? ? e.printStackTrace();? ? ? ? }? ? ? ? return?res;? ? }?? ? public?static void main(String[] args) throws Exception {? ? ? ? if?(args.length != 4) {? ? ? ? ? ? System.out.println("Usage: Client host port dataSize count");? ? ? ? ? ? System.exit(0);? ? ? ? }?? ? ? ? String?host = args[0];? ? ? ? int?port = Integer.parseInt(args[1]);? ? ? ? int?size = Integer.parseInt(args[2]);? ? ? ? int?count = Integer.parseInt(args[3]);? ? ? ? new?Client(Utils.getProtocol(), host, port, size, count).run();? ? }}5.参考资料
(1) Avro Documentation: http://avro.apache.org/docs/current/index.html