Thrift最初由Facebook研發,主要用於各個服務之間的RPC通訊,支持跨語言,經常使用的語言好比C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml都支持。Thrift是一個典型的CS(客戶端/服務端)結構,客戶端和服務端能夠使用不一樣的語言開發。既然客戶端和服務端能使用不一樣的語言開發,那麼必定就要有一種中間語言來關聯客戶端和服務端的語言,沒錯,這種語言就是IDL(Interface Description Language)。
html
下載地址
windows 下面下載exe,thrift在linux下面也有對應的安裝方式。將thrift-0.9.3.exe 下載下來重命名爲thrift.exe,並拷貝到windows--->system32裏面。
java
<dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.9.3</version> </dependency>
git clone https://git-wip-us.apache.org/repos/asf/thrift.git thrift cd thrift
1.數據類型linux
2.服務端編碼基本步驟:git
3.客戶端編碼基本步驟:apache
4.數據傳輸協議windows
1.建立文件,在D:\thrift下創建hello.thrift文件maven
namespace java com.tony.thrift.demo service HelloWorldService { string sayHello(1:string username) }
thrift -r -gen java hello.thrift
ide
2,將上述截圖生成的文件拷貝到工程中。測試
HelloWorldService
編碼
public class HelloWorldService { public interface Iface { public String sayHello(String username) throws org.apache.thrift.TException; } }
HelloWorldImpl
public class HelloWorldImpl implements HelloWorldService.Iface{ @Override public String sayHello(String username) throws TException { return "Hi," + username + " welcome to thrift"; } }
HelloServerDemo
public class HelloServerDemo { public static final int SERVER_PORT = 7911; public void startServer() { try { System.out.println("Server start ...."); TProcessor tprocessor = new HelloWorldService.Processor<HelloWorldService.Iface>(new HelloWorldImpl()); TServerSocket serverTransport = new TServerSocket(SERVER_PORT); TServer.Args tArgs = new TServer.Args(serverTransport); tArgs.processor(tprocessor); tArgs.protocolFactory(new TBinaryProtocol.Factory()); TServer server = new TSimpleServer(tArgs); server.serve(); } catch (Exception e) { System.out.println("Server start error!!!"); e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { HelloServerDemo server = new HelloServerDemo(); server.startServer(); } }
HelloClientDemo
public class HelloClientDemo { public static final String SERVER_IP = "localhost"; public static final int SERVER_PORT = 7911; public static final int TIMEOUT = 30000; public void startClient(String userName) { TTransport transport = null; try { transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT); TProtocol protocol = new TBinaryProtocol(transport); HelloWorldService.Client client = new HelloWorldService.Client(protocol); transport.open(); String result = client.sayHello(userName); System.out.println(result); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } finally { if (null != transport) { transport.close(); } } } public static void main(String[] args) { HelloClientDemo client = new HelloClientDemo(); client.startClient("tony"); } }
https://thrift.apache.org/download