1.使用windows實現,首先在apache官網下載一個thrift的編譯工具,在項目中建一個文件叫add.thrift的文件,內容以下:java
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 的文件apache
2 把這個文件添加到項目中(須要的jar包有兩個,一個是thrift的jar包,要本身去生成,一個是slf4j jar包),目錄結構以下:windows
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 編寫服務端,代碼以下ide
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運行服務器端和客戶端,結果客戶端爲300spa