Apache Thrift系列之概述与入门

Thrift是一个轻量级跨语言远程服务调用框架,最初由Facebook开发,后面进入Apache开源项目。它通过自身的IDL中间语言, 并借助代码生成引擎生成各种主流语言的RPC服务端/客户端模板代码。

Thrift支持多种不同的编程语言,包括C++JavaPythonPHPRuby等,本系列主要讲述基于Java语言的Thrift的配置方式和具体使用。

正文

Thrift的技术栈

Thrift软件栈的定义非常的清晰, 使得各个组件能够松散的耦合, 针对不同的应用场景, 选择不同是方式去搭建服务。

 

 

 

Thrift软件栈分层从下向上分别为:传输层(Transport Layer)、协议层(Protocol Layer)、处理层(Processor Layer)和服务层(Server Layer)。

  • 传输层(Transport Layer):传输层负责直接从网络中读取写入数据,它定义了具体的网络传输协议;比如说TCP/IP传输等。

  • 协议层(Protocol Layer):协议层定义了数据传输格式,负责网络传输数据的序列化反序列化;比如说JSONXML二进制数据等。

  • 处理层(Processor Layer):处理层是由具体的IDL接口描述语言)生成的,封装了具体的底层网络传输序列化方式,并委托给用户实现的Handler进行处理。

  • 服务层(Server Layer):整合上述组件,提供具体的网络线程/IO服务模型,形成最终的服务。

Thrift的特性

(一) 开发速度快

通过编写RPC接口Thrift IDL文件,利用编译生成器自动生成服务端骨架(Skeletons)和客户端桩(Stubs)。从而省去开发者自定义维护接口编解码消息传输服务器多线程模型等基础工作。

  • 服务端:只需要按照服务骨架接口,编写好具体的业务处理程序(Handler)即实现类即可。
  • 客户端:只需要拷贝IDL定义好的客户端桩服务对象,然后就像调用本地对象的方法一样调用远端服务。

(二) 接口维护简单

通过维护Thrift格式的IDL(接口描述语言)文件(注意写好注释),即可作为给Client使用的接口文档使用,也自动生成接口代码,始终保持代码和文档的一致性。且Thrift协议可灵活支持接口可扩展性

(三) 学习成本低

因为其来自Google Protobuf开发团队,所以其IDL文件风格类似Google Protobuf,且更加易读易懂;特别是RPC服务接口的风格就像写一个面向对象Class一样简单。

初学者只需参照:thrift.apache.org/,一个多小时就可以理解Thrift IDL文件的语法使用。

(四) 多语言/跨语言支持

Thrift支持C++JavaPythonPHPRubyErlangPerlHaskellC#CocoaJavaScriptNode.jsSmalltalk等多种语言,即可生成上述语言的服务器端客户端程序

对于我们经常使用的JavaPHPPythonC++支持良好,虽然对iOS环境的Objective-C(Cocoa)支持稍逊,但也完全满足我们的使用要求。

(五) 稳定/广泛使用

Thrift在很多开源项目中已经被验证是稳定高效的,例如CassandraHadoopHBase等;国外在Facebook中有广泛使用,国内包括百度、美团小米、和饿了么等公司。

 

 

 

Thrift的数据类型

Thrift 脚本可定义的数据类型包括以下几种类型:

  1. 基本类型:
    • bool: 布尔值
    • byte: 8位有符号整数
    • i16: 16位有符号整数
    • i32: 32位有符号整数
    • i64: 64位有符号整数
    • double: 64位浮点数
    • string: UTF-8编码的字符串
    • binary: 二进制串
  2. 结构体类型:
    • struct: 定义的结构体对象
  3. 容器类型:
    • list: 有序元素列表
    • set: 无序无重复元素集合
    • map: 有序的key/value集合
  4. 异常类型:
    • exception: 异常类型
  5. 服务类型:
    • service: 具体对应服务的类

Thrift的协议

Thrift可以让用户选择客户端服务端之间传输通信协议的类别,在传输协议上总体划分为文本(text)和二进制(binary)传输协议。为节约带宽提高传输效率,一般情况下使用二进制类型的传输协议为多数,有时还会使用基于文本类型的协议,这需要根据项目/产品中的实际需求。常用协议有以下几种:

  • TBinaryProtocol:二进制编码格式进行数据传输
  • TCompactProtocol:高效率的、密集二进制编码格式进行数据传输
  • TJSONProtocol: 使用JSON文本的数据编码协议进行数据传输
  • TSimpleJSONProtocol:只提供JSON只写的协议,适用于通过脚本语言解析

Thrift的传输层

常用的传输层有以下几种:

  • TSocket:使用阻塞式I/O进行传输,是最常见的模式
  • TNonblockingTransport:使用非阻塞方式,用于构建异步客户端
  • TFramedTransport:使用非阻塞方式,按块的大小进行传输,类似于Java中的NIO

Thrift的服务端类型

  • TSimpleServer:单线程服务器端,使用标准的阻塞式I/O
  • TThreadPoolServer:多线程服务器端,使用标准的阻塞式I/O
  • TNonblockingServer:单线程服务器端,使用非阻塞式I/O
  • THsHaServer:半同步半异步服务器端,基于非阻塞式IO读写和多线程工作任务处理
  • TThreadedSelectorServer:多线程选择器服务器端,对THsHaServer异步IO模型上进行增强

Thrift入门示例

(一) 编写Thrift IDL文件

a). 下载0.10.0Thrift IDL编译器,下载地址:http://thrift.apache.org/docs/install。 通过编译生成器生成.java接口的类文件。

 

 

 

b). 下载Windows安装环境的.exe文件,将thrift.exe的路径加入环境变量中。在Idea上安装Thrift编辑插件。

 

 

 

c). 编写hello.thriftIDL文件:

service HelloWorldService {
  string say(1: string username)
}
复制代码

d). 使用代码生成工具生成代码,执行以下命令:

thrift -gen java hello.thrift
复制代码

e). 由于未指定代码生成的目标目录,生成的类文件默认存放在gen-java目录下。这里生成一个HelloWorldService.java类文件,文件大小超过数千行,下面截取一部分核心代码

public class HelloWorldService {
    public interface Iface {
        public String say(String username) throws org.apache.thrift.TException;
    }

    public interface AsyncIface {
        public void say(String username, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws org.apache.thrift.TException;
    }

    public static class Client extends org.apache.thrift.TServiceClient implements Iface {
        public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
            public Factory() {
            }

            public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
                return new Client(prot);
            }

            public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
                return new Client(iprot, oprot);
            }
        }

        public Client(org.apache.thrift.protocol.TProtocol prot) {
            super(prot, prot);
        }

        public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
            super(iprot, oprot);
        }

        public String say(String username) throws org.apache.thrift.TException {
            send_say(username);
            return recv_say();
        }
        // 省略.....
    }

    public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
        public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
            private org.apache.thrift.async.TAsyncClientManager clientManager;
            private org.apache.thrift.protocol.TProtocolFactory protocolFactory;

            public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
                this.clientManager = clientManager;
                this.protocolFactory = protocolFactory;
            }

            public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
                return new AsyncClient(protocolFactory, clientManager, transport);
            }
        }

        public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
            super(protocolFactory, clientManager, transport);
        }

        public void say(String username, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws org.apache.thrift.TException {
            checkReady();
            say_call method_call = new say_call(username, resultHandler, this, ___protocolFactory, ___transport);
            this.___currentMethod = method_call;
            ___manager.call(method_call);
        }
        // 省略.....
    }
    // 省略.....
}
复制代码

对于开发人员而言,使用原生的Thrift框架,仅需要关注以下四个核心内部接口/类Iface, AsyncIface, ClientAsyncClient

  • Iface服务端通过实现HelloWorldService.Iface接口,向客户端的提供具体的同步业务逻辑。
  • AsyncIface服务端通过实现HelloWorldService.Iface接口,向客户端的提供具体的异步业务逻辑。
  • Client客户端通过HelloWorldService.Client的实例对象,以同步的方式访问服务端提供的服务方法。
  • AsyncClient客户端通过HelloWorldService.AsyncClient的实例对象,以异步的方式访问服务端提供的服务方法。

(二) 新建Maven工程

a). 新建maven工程,引入thrift的依赖,这里使用的是版本0.10.0

  <dependency>
      <groupId>org.apache.thrift</groupId>
      <artifactId>libthrift</artifactId>
      <version>0.10.0</version>
  </dependency>
复制代码

b). 将生成类的HelloWorldService.java源文件拷贝进项目源文件目录中,并实现HelloWorldService.Iface的定义的say()方法。

HelloWorldServiceImpl.java

public class HelloWorldServiceImpl implements HelloWorldService.Iface {
    @Override
    public String say(String username) throws TException {
        return "Hello " + username;
    }
}
复制代码

c). 服务器端程序编写:

SimpleServer.java

public class SimpleServer {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(ServerConfig.SERVER_PORT);
        TServerSocket serverTransport = new TServerSocket(serverSocket);
        HelloWorldService.Processor processor =
                new HelloWorldService.Processor<HelloWorldService.Iface>(new HelloWorldServiceImpl());

        TBinaryProtocol.Factory protocolFactory = new TBinaryProtocol.Factory();
        TSimpleServer.Args tArgs = new TSimpleServer.Args(serverTransport);
        tArgs.processor(processor);
        tArgs.protocolFactory(protocolFactory);

        // 简单的单线程服务模型 一般用于测试
        TServer tServer = new TSimpleServer(tArgs);
        System.out.println("Running Simple Server");
        tServer.serve();
    }
}
复制代码

d). 客户端程序编写:

SimpleClient.java

public class SimpleClient {
    public static void main(String[] args) {
        TTransport transport = null;
        try {
            transport = new TSocket(ServerConfig.SERVER_IP, ServerConfig.SERVER_PORT, ServerConfig.TIMEOUT);
            TProtocol protocol = new TBinaryProtocol(transport);
            HelloWorldService.Client client = new HelloWorldService.Client(protocol);
            transport.open();

            String result = client.say("Leo");
            System.out.println("Result =: " + result);
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            if (null != transport) {
                transport.close();
            }
        }
    }
}
复制代码

e). 运行服务端程序,服务端指定端口监听客户端连接请求,控制台输出启动日志:

 

 

 

f). 运行客户端程序,客户端通过网络请求HelloWorldServicesay()方法的具体实现,控制台输出返回结果:

 

 

 

这里使用的一个基于单线程同步简单服务模型,一般仅用于入门学习和测试!

  1. Apache Thrift系列详解(一) - 概述与入门

  2. Apache Thrift系列详解(二) - 网络服务模型

  3. Apache Thrift系列详解(三) - 序列化机制

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apache Thrift 是一种高效且跨语言的远程服务调用框架,它可以让你使用不同的编程语言实现客户端和服务器端,并且在它们之间进行通信。下面是使用 Java 快速入门 Apache Thrift 的步骤: 1. 安装 Thrift 首先,你需要从 Apache Thrift 的官方网站(https://thrift.apache.org/)下载并安装 Thrift。 2. 定义接口文件 在 Thrift 中,你需要定义一个接口文件,它描述了你的服务接口和数据类型。下面是一个简单的示例: ``` namespace java com.example service MyService { string sayHello(1: string name) } ``` 上面的代码定义了一个名为 MyService 的服务,它有一个名为 sayHello 的方法,它接受一个名为 name 的字符串参数,并返回一个字符串。 3. 生成代码 使用 Thrift 编译器(thrift)来生成 Java 代码: ``` thrift --gen java MyService.thrift ``` 这将生成一个名为 MyService.java 的 Java 接口文件,以及一些用于序列化和反序列化的辅助类。 4. 实现服务 你需要编写一个实现 MyService 接口的 Java 类,例如: ``` public class MyServiceImpl implements MyService.Iface { public String sayHello(String name) throws TException { return "Hello, " + name + "!"; } } ``` 上面的代码实现了 sayHello 方法,并返回一个带有名称的问候语。 5. 启动服务器 你需要编写一个 Java 服务器,以便可以在其中运行 MyServiceImpl。以下是一个简单的示例: ``` public class MyServer { public static void main(String[] args) throws Exception { TServerTransport serverTransport = new TServerSocket(9090); TServer server = new TSimpleServer(new Args(serverTransport).processor(new MyService.Processor(new MyServiceImpl()))); System.out.println("Starting the server..."); server.serve(); } } ``` 上面的代码创建了一个 TSimpleServer 实例,并将其绑定到本地的 9090 端口。它还将 MyServiceImpl 的实例添加到 MyService.Processor 中,以便服务器可以调用 MyServiceImpl 中实现的方法。 6. 编写客户端 你需要编写一个 Java 客户端,以便可以调用 MyServiceImpl 中实现的方法。以下是一个简单的示例: ``` public class MyClient { public static void main(String[] args) throws Exception { TTransport transport = new TSocket("localhost", 9090); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); MyService.Client client = new MyService.Client(protocol); String result = client.sayHello("World"); System.out.println(result); transport.close(); } } ``` 上面的代码创建了一个 TSocket 实例,并将其连接到本地的 9090 端口。它还创建了一个 MyService.Client 实例,并使用它来调用 MyServiceImpl 中实现的 sayHello 方法。 以上就是使用 Java 快速入门 Apache Thrift 的步骤。你可以通过阅读 Thrift 的官方文档来了解更多信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值