1 介绍
thrift一个RPC框架,可以用来远程通信
2 生成接口代码
1.下载thrift,thrift-0.10.0.exe
2.将编写的hello.thrift文件,放置在和下载好的thrift-0.10.0.exe同一个目录之下,
然后执行如下操作即可产生相关代码~
thrift文件的相关规范见 https://blog.csdn.net/finallygo/article/details/84691611
hello.thrift
namespace java cc.study
service Hello{
string helloWorld()
}
thrift-0.10.0.exe -gen java hello.thrift
运行该命令之后,在该目录下将生成gen-java文件,其中就有需要的接口文件【Hello.java】
3 开发
服务端编写的一般步骤:
- 创建Handler(实现接口)
- 基于Handler创建Processor
- 创建Transport(通信方式)
- 创建Protocol方式(设定传输格式)
- 基于Processor, Transport和Protocol创建Server
- 运行Server
客户端编写的一般步骤:
- 创建Transport
- 创建Protocol方式
- 基于Transport和Protocol创建Client
- 运行Client的方法
4 thrift server
其中Hello为生成的接口文件,不需要改动
4.1 引入依赖
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.10.0</version>
</dependency>
4.2 实现类
public class HelloServiceImp implements Hello.Iface {
@Override
public String helloWorld() throws TException {
System.out.println("thrift hello !!!");
return "hello world!!";
}
}
4.3 server
public class HelloServerDemo {
public static void main(String[] args) throws IOException, TTransportException {
final int SERVER_PORT = 8090;
// 1 创建 processor
Hello.Processor processor = new Hello.Processor(new HelloServiceImp());
// 2 创建transport
ServerSocket socket = new ServerSocket(SERVER_PORT);
TServerSocket serverTransport = new TServerSocket(socket);
// 3 基于Processor, Transport和Protocol创建Server
TServer.Args tArgs = new TServer.Args(serverTransport);
tArgs.processor(processor);
tArgs.protocolFactory(new TBinaryProtocol.Factory());// 设定传输格式
TServer server = new TSimpleServer(tArgs);
System.out.println("Running server...");
// 4 启动server
server.serve();
}
}
5 thrift client
其中Hello为生成的接口文件,不需要改动,同样引入thrift依赖包
5.1 client
public class HelloClient {
public static final String SERVER_IP = "localhost";
public static final int SERVER_PORT = 8090;
public static final int TIMEOUT = 30000;
public void startClient() {
TTransport transport = null;
try {
//1. 创建Transport
transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
// 2. 创建Protocol方式
TProtocol protocol = new TBinaryProtocol(transport);
//3. 基于Transport和Protocol创建Client
Hello.Client client = new Hello.Client(
protocol);
transport.open();
//4. 运行Client的方法
String result = client.helloWorld();
System.out.println("Thrify client result =: " + result);
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
} finally {
if (null != transport) {
transport.close();
}
}
}
public static void main(String[] args) {
HelloClient client = new HelloClient();
client.startClient();
}
}