Apache Thrift 是一個高性能、跨語言的 RPC 框架,通過定義中立的 IDL 文件生成各語言代碼,實現服務間無縫調用。本文基於 Thrift 0.9.3,演示在 IntelliJ IDEA 中構建 Maven 項目,從 IDL 定義到服務端/客戶端代碼編寫的全過程。
<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.7.5</version>
</dependency>
HelloWorld.thriftnamespace java com.thrift.demo
service HelloWorldService {
string sayHello(1: string username)
}
在命令行執行:
thrift.exe -gen java HelloWorld.thrift
生成的 gen-java/com/thrift/demo/HelloWorldService.java 包含 Iface、Processor、Client 等核心類,複製到項目 src/main/java 對應包下。
package com.jmust.thrift.demo;
import org.apache.thrift.TException;
public class HelloWorldImpl implements HelloWorldService.Iface {
@Override
public String sayHello(String username) throws TException {
return "Hi, " + username + " Welcome to my blog https://www.cnblogs.com/zfygiser";
}
}
HelloServerpackage com.jmust.thrift.demo;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
public class HelloServer {
public static final int SERVER_PORT = 7099;
public void startServer() {
try {
System.out.println("HelloWorld Server start...");
TServerSocket serverTransport = new TServerSocket(SERVER_PORT);
TProcessor processor = new HelloWorldService.Processor(new HelloWorldImpl());
TBinaryProtocol.Factory protoFactory = new TBinaryProtocol.Factory(true, true);
TServer server = new TSimpleServer(
new TServer.Args(serverTransport)
.processor(processor)
.protocolFactory(protoFactory)
);
server.serve();
} catch (Exception e) {
System.err.println("Server start error");
e.printStackTrace();
}
}
public static void main(String[] args) {
new HelloServer().startServer();
}
}
Clientpackage com.jmust.thrift.demo;
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 final int SERVER_PORT = 7099;
public static final String SERVER_IP = "localhost";
public void startClient(String username) {
TTransport transport = null;
try {
transport = new TSocket(SERVER_IP, SERVER_PORT);
TProtocol protocol = new TBinaryProtocol(transport);
HelloWorldService.Client client = new HelloWorldService.Client(protocol);
transport.open();
String result = client.sayHello(username);
System.out.println("Thrift client result = " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (transport != null) transport.close();
}
}
public static void main(String[] args) {
new Client().startClient("zfy");
}
}
HelloServer.main,控制台顯示 HelloWorld Server start...Client.main,輸出:Thrift client result = Hi, zfy Welcome to my blog ...


本示例展示了 Thrift 在 Java 中的最小化落地流程,實際生產中可根據需要替換為 TThreadPoolServer、TNonblockingServer 等高性能服務模型,並加入異常處理、連接池、監控等增強功能。