java如何调用thrift
Java 调用 Thrift 的基本流程
Thrift 是一个跨语言的 RPC 框架,Java 调用 Thrift 需要先定义接口文件,生成代码,再实现服务端和客户端。
定义 Thrift 接口文件
创建 .thrift 文件,定义接口和数据结构。例如 example.thrift:
namespace java com.example.thrift
service HelloService {
string sayHello(1:string name)
}
生成 Java 代码
使用 Thrift 编译器生成 Java 代码:
thrift --gen java example.thrift
生成的代码会包含客户端和服务端的接口定义。
实现服务端
创建服务端实现类:
public class HelloServiceImpl implements HelloService.Iface {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
}
启动服务端:
public class Server {
public static void main(String[] args) {
try {
TServerTransport serverTransport = new TServerSocket(9090);
HelloService.Processor<HelloServiceImpl> processor =
new HelloService.Processor<>(new HelloServiceImpl());
TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
}
实现客户端
创建客户端调用代码:
public class Client {
public static void main(String[] args) {
try {
TTransport transport = new TSocket("localhost", 9090);
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
HelloService.Client client = new HelloService.Client(protocol);
System.out.println(client.sayHello("World"));
transport.close();
} catch (TException e) {
e.printStackTrace();
}
}
}
使用 Maven 管理依赖
在 pom.xml 中添加 Thrift 依赖:
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.16.0</version>
</dependency>
高级配置
可以使用 TNonblockingServer 或 THsHaServer 提高性能:

TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(9090);
HelloService.Processor<HelloServiceImpl> processor = new HelloService.Processor<>(new HelloServiceImpl());
TServer server = new TNonblockingServer(new Args(serverTransport).processor(processor));
server.serve();
注意事项
确保客户端和服务端使用的协议一致(如 TBinaryProtocol)。如果跨语言调用,需确保接口定义在各语言中兼容。






