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