thrift linux java,Thrift, Protocol Buffers installation and Java code howto

I. Thrift installation and Java code

1. build and install thrift

install boost

cd /tools/jam

./build_dist.sh

# linux* will depends the platform

cp stage/bin.linux*/bjam

# build boost, use bjam will faster

cd

./configure –without-icu –prefix=/usr/local/boost

./bjam -toolset=gcc –build-type=release install –prefix=/usr/local/boost

# build thrift

./bootstrap.sh

./configure –with-boost=/usr/local

make

make install

2. Build Thrift java library

install apache ant if necessary

cd lib/java/

ant

get libthrift.jar

3. Create .thrift file and gen Java code

(See http://wiki.apache.org/thrift/Tutorial for more .thrift tutorial info)

tim.thrift

struct dns_record {

1: string key,

2: string value,

3: string type = 'A',

4: i32 ttl = 86400,

5: string first,

6: string last

}

service TestDns {

dns_record test(1:string q);

}

/bin/thrift –gen java tim.thrift

code will be generated in gen-java/*.java

4. Write java code

// new object

dns_record dr = new dns_record(key, value, type, ttl, first, last)

// serialize

TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());

TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());

byte[] bytes = serializer.serialize(dr);

II. Protocol Buffers install and Java code

1. Build and install Protocol buffers

./configure

make

make install

2. Build protobuf Java library

install maven if not necessary

cd protobuf/java

mvn test

mvn package

get jar from target/protobuf-java-x.x.x.jar

3. Create .proto file and gen Java code

tim.proto

package dns;

message DnsRecord {

required string key = 1;

required string value = 2;

required string first = 3;

required string last = 4;

optional string type = 5 [default = "A"];

optional int32  ttl = 6 [default = 86400];

}

message DnsResponse {

repeated DnsRecord records = 1;

}

bin/protoc –java_out . tim.proto

4. Write Java code

// protocol buffer need a builder to create object

Dns.DnsRecord.Builder b = Dns.DnsRecord.newBuilder();

b.setKey("key");

b.setValue("value...");

...

b.builder();

byte[] bytes = dr.toByteArray();

Dns.DnsRecord dr2 = Dns.DnsRecord.parseFrom(bytes);

III. Resources

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值