Thrift使用

介绍thrift基本用法。

install

1
brew install thrift

hello example

maven

1
2
3
4
5
6
7
8
9
10
11
12
<dependencies>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.9.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
</dependencies>

IDL

编写thrift IDL文件hello.thrift,用于生成java代码

1
2
3
4
5
namespace java demo

service HelloService {
string hi()
}

generate

执行名声,生成java代码,

1
thrift -gen java hello.thrift

此时,会在当前目录下生成java-gen文件夹,其中包含所需要的thrift接口文件HelloService.java

impl

上步中生成了相应的HelloServie.Iface接口,所以需要实现该接口文件,

1
2
3
4
5
6
7
package demo;

public class HelloImpl implements HelloService.Iface {
public String hi() {
return "Hi!!!";
}
}

server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package demo;

import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;

public class Server {
public static void main(String[] args) {
HelloImpl hello = new HelloImpl();
final HelloService.Processor<HelloImpl> p =
new HelloService.Processor<HelloImpl>(hello);

new Thread(new Runnable() {
public void run() {
try {
TServerTransport st = new TServerSocket(9000);
TServer tServer = new TSimpleServer(new TServer.Args(st).processor(p));
System.out.println("Starting ...");
tServer.serve();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}

client

注意server使用的端口9000,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package demo;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class Client {
public static void main(String[] args) throws TException {
TTransport ts = new TSocket("localhost", 9000);
ts.open();

TProtocol p = new TBinaryProtocol(ts);
HelloService.Client client = new HelloService.Client(p);

System.out.println(client.hi());

ts.close();
}
}