thrift的简单实现

时间:2023-03-09 02:41:43
thrift的简单实现

1.使用windows实现,首先在apache官网下载一个thrift的编译工具,在项目中建一个文件叫add.thrift的文件,内容如下:

namespace java com.vipshop.sample.server

service AdditionService{
i32 add(1:i32 n1,2:i32 n2)
}

使用下载的thrift工具进行编译,命令如下thrift --gen java add.thrift(本人使用的是java实现)  编译后会生成一个叫AdditionService.java 的文件

2 把这个文件添加到项目中(需要的jar包有两个,一个是thrift的jar包,要自己去生成,一个是slf4j  jar包),目录结构如下:

thrift的简单实现

3 新建一个名叫AdditionServiceHandle的java文件,来实现我们在AdditionService中所需要实现的方法

import org.apache.thrift.TException;

public class AdditionServiceHandle implements AdditionService.Iface{

    @Override
public int add(int n1, int n2) throws TException {
// TODO Auto-generated method stub
return n1+n2;
} }

4 编写服务端,代码如下

import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport; public class MyServer { public static void startsImpleServer(AdditionService.Processor<AdditionServiceHandle> processor){
try
{
TServerTransport serverTransport=new TServerSocket(9090);
TServer server=new TSimpleServer(new TServer.Args(serverTransport).processor(processor)); System.out.println("starting the simple server....");
server.serve();
}
catch (Exception e)
{
// TODO: handle exception
}
} public static void main(String[] args) {
startsImpleServer(new AdditionService.Processor<AdditionServiceHandle>(new AdditionServiceHandle()));
} }

5 编写客户端

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 AdditionClient {
public static void main(String[] args) {
try
{
TTransport transport;
transport=new TSocket("localhost",9090);
transport.open(); TProtocol protocol=new TBinaryProtocol(transport);
AdditionService.Client client=new AdditionService.Client(protocol);
System.out.println(client.add(100, 200));
transport.close();
}
catch (Exception e)
{
// TODO: handle exception
}
}
}

6运行服务器端和客户端,结果客户端为300