一、配置 Thrift 环境
1.下载 Windows 版本的 thrift.exe 文件:点我下载
2.把下载文件重命名为 thrift.exe,放在英文目录下,如 D:\thrift
3.添加 thrift 的目录 D:\thrift 到 Path 环境变量中
4.在 cmd 中输入 thrift 或 thrift -version 后回车,如图则 thrift 环境配置成功
二、定义和编译 IDL 接口
1.定义 IDL 接口文件,创建 HelloWorldService.thrift
service HelloWorldService {
/**
* 定义接口
* @param str 字符串
* @return 字符串
*
* thrift 的基本类型 string 首字母小写
*/
string sayHello(1:string str)
}
2.编译 HelloWorldService.thrift 接口文件,在 cmd 中 输入 thrift -gen java HelloWorldService.thrift 后回车
然后在桌面会生成一个叫 gen-java 的文件夹,里面的 HelloWorldService.java 是生成的 java 接口文件
三、服务端
准备:使用 IntelliJ IDEA 创建 Maven 工程 HelloWorld,把编译生成的 java 接口文件 HelloWorldService.java 复制到项目中
1.在 pom.xml 文件的 project 标签下添加
<dependencies>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.10.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
</dependencies>
2.若 IDL 接口文件报关于 @Override 的错误,在 pom.xml 文件的 project 标签下添加
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
3.创建类 HelloWorldServiceImpl,实现 HelloWorldService.Iface 接口
public class HelloWorldServiceImpl implements HelloWorldService.Iface {
public String sayHello(String str) {
// str 等于 null 或空字符串
if (str == null || "".equals(str)) {
// 返回字符串 "Hello World"
return "Hello World";
}
return "Hello " + str;
}
}
4.创建类 ThriftServer 服务端(等待客户端访问,监听端口:9999)
public class ThriftServer {
public static void main(String[] args) throws TTransportException {
// 服务端监听端口:9999
TServerTransport socket = new TServerSocket(9999);
HelloWorldService.Processor processor = new HelloWorldService.Processor(new HelloWorldServiceImpl());
TServer.Args serverArgs = new TServer.Args(socket);
serverArgs.processor(processor);
TSimpleServer server = new TSimpleServer(serverArgs);
System.out.println("服务端已开启...");
server.serve();
}
}
四、客户端
创建类 ThriftClient 客户端(访问端口:9999)
public class ThriftClient {
public static void main(String[] args) throws TException {
// IP:localhost、端口:9999
TTransport transport = new TSocket("localhost", 9999);
TProtocol protocol = new TBinaryProtocol(transport);
HelloWorldService.Client client = new HelloWorldService.Client(protocol);
if (!transport.isOpen()) {
transport.open();
}
System.out.println(client.sayHello("thrift"));
transport.close();
}
}
五、测试
1.启动服务端,执行 ThriftServer.java 的 main() 方法
控制台打印:服务器已开启
2.运行客户端,执行 ThriftClient.java 的 main() 方法
控制台打印:Hello Thrift