当前版本:jdk1.8、thrift 0.16.0
1. 声明当前内容主要简单的使用thrift实现客户端和服务端,主要从apache iotdb中得知,详情可以查看官方
1. 下载thrift(apache 官方访问不是很好可以直接使用华为mirror)
下载即可(本人使用exe的,建议也下载gz的,gz的中有tutorial)
1.将gz中的tutorial中的shade.thrift和tutorial.thrift拷贝到thrift-0.16.0.exe同级目录下
2.使用cmd并执行:thrift-0.16.0.exe -r --gen java tutorial.thrift
此时在该目录下会生成gen-java文件并会生成对应的代码
3. 将gz中的tutorial中的java内src内容部分考入到项目,同时将上面生成的也放入项目中
4. 修改部分JavaClient和JavaServer中的代码(只使用simple即可)
5. 启动JavaServer然后在启动JavaClient结果如下
发现执行成功!通过查看代码和tutorial.thrift文件可以得到具体实现
1. 创建test.thrift
// 定义一个服务就是HiService
service HiService {
void hello()
}
2. 使用命令生成HiService.java文件
3. 实现HiService中的Iface(即server端的处理)
public class HiServiceHandler implements HiService.Iface{
@Override
public void hello() throws TException {
System.out.println("hello called !");
}
}
4. 编写HiServiceServer和HiServiceClient
public class HiServiceClient {
public static void main(String[] args) {
TTransport transport;
try {
transport = new TSocket("localhost", 9090);
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
HiService.Client client = new HiService.Client(protocol);
client.hello();
System.out.println("send msg to HiServiceServer!");
transport.close();
} catch (TException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class HiServiceServer {
public static void main(String[] args) {
HiServiceHandler handler = new HiServiceHandler();
TProcessor processor = new HiService.Processor(handler);
try {
TServerTransport serverTransport = new TServerSocket(9090);
TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
System.out.println("Starting the simple server...");
server.serve();
} catch (Exception e) {
e.printStackTrace();
}
}
}
5. 测试
实现客户端和服务端非常容易
1. thrift使用thrift来限定当前的客户端和服务端的交流,可以快速实现rpc通信程序
2. 必须使用thrift特定的语法方式实现,必须学会定义



