Thrift是一种接口描述语言和二进制通信协议,它被用来定义和建立跨语言的服务。它被看成一个远程过程调用(RPC)框架来使用,是由Facebook为“大规模跨语言服务开发”而开发的。它经过一个代码生成引擎联合了一个软件栈,来建立不一样程度的、无缝的跨平台高效服务,能够使用C#、C++(基于POSIX兼容系统)、Cappuccino、Cocoa、Delphi、Erlang、Go、Haskell、Java、Node.js、OCaml、Perl、PHP、Python、Ruby和Smalltalk。另外,Thrift早期由Facebook开发,目前已成为Apache软件基金会的开源项目。java
相似于计算机网络,Thrift包含一套完整的栈来建立客户端和服务端程序。apache
根据官网,使用Thrift前须要下载Thrift而且构建和安装Thrift编译器。
在使用Thrift进行编程时,须要如下几步(详细过程可见Apache Thrift Tutorial):编程
namespace java com.lpf.service service HelloService { string hello(1: string name); }
thrift --gen <language> <Thrift filename>
生成的Java关键代码以下:(部分代码)服务器
package com.lpf.service; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.11.0)", date = "2018-06-08") public class HelloService { public interface Iface { public String sayHello(String username) throws org.apache.thrift.TException; } }
把生成的HelloService引入工程中网络
(1)添加pom依赖数据结构
<dependencies> <dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.11.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> </dependencies>
(2)编写接口实现类 HelloServiceImpl多线程
public class HelloServiceImpl implements HelloService.Iface { public HelloServiceImpl() { } @Override public String sayHello(String username) { return "Hi," + username + " ,Welcome to the thrift's world !"; } }
(3)启动监听HelloServerDemo架构
public class HelloServerDemo { public static void main(String[] args) throws TTransportException { Logger logger = LoggerFactory.getLogger(HelloServerDemo.class); int port= 9000 ; // *) 传输层(Transport), 设置监听端口为9000 TServerSocket serverTransport = new TServerSocket(port); // *) 协议层 TBinaryProtocol.Factory protocolFactory = new TBinaryProtocol.Factory(true, true); // *) 处理层(Processor) HelloServiceImpl handler = new HelloServiceImpl(); HelloService.Processor<HelloServiceImpl> processor = new HelloService.Processor<HelloServiceImpl>(handler); // *) 服务层(Server) TServer server = new TThreadPoolServer( new TThreadPoolServer.Args(serverTransport) .protocolFactory(protocolFactory) .processor(processor)); // *) 启动监听服务 server.serve(); } }
4.客服端远程调用app
(1)添加pom依赖 同上框架
(2)编写客户端测试类
一样的客户端也须要把生成的接口类引入项目中
public class HelloClientDemo { public static void main(String[] args) throws TException { // *) 传输层 TTransport transport = new TSocket("localhost", 9000); transport.open(); // *) 协议层, 与服务端对应 TProtocol protocol = new TBinaryProtocol(transport); // *) 建立RPC客户端 HelloService.Client client = new HelloService.Client(protocol); // *) 调用服务 System.out.println(client.sayHello("lpf")); // *) 关闭句柄 transport.close(); } }
先运行服务端,后运行客户端,观察结果,能够看到客户端输出结果: