Thrift开发接口

来源:互联网 发布:geogebra mac 编辑:程序博客网 时间:2024/06/06 10:39

Thrift是facebook技术核心框架之一,不同开发语言开发的服务可以通过该框架实现通信。Thrift通过接口定义语言 (interface definition language,IDL) 来定义数据类型和服务,Thrift接口定义文件由Thrift代码编译器生成thrift目标语言的代码(目前支持C++,Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk和OCaml),并由生成的代码负责RPC协议层和传输层的实现。

  简而言之,开发者只需准备一份thrift脚本,通过thrift code generator(像gcc那样输入一个命令)就能生成所要求的开发语言代码。不支持windows。

  Thrift侧重点是构建跨语言的可伸缩的服务,特点就是支持的语言多,同时提供了完整的RPC service framework,可以很方便的直接构建服务,不需要做太多其他的工作。

1、编写Thrift IDL,保存为DevelopApiService.thrift文件

namespace java cn.cstor.cproc.java.thrift  struct UserInfo {      1: required string userName,      2: optional string uid,3: required string accessId,4: optional string state}struct AppInfo {1: required UserInfo userInfo,      2: optional string aid,4: required string appId,5: optional string appstate}struct ColumnInfo {      1: required string columnName,      2: required string type,3: optional string desc}struct TableInfo {      1: required string tableName,      2: required string key,3: required list columns,4: optional string desc,5: optional string tbstate}struct Row {      1: required map values}struct ReObject {      1: optional bool success,      2: optional list talInfos,3: optional list data,4: optional string msg}enum CompareType {    EQUAL,      GREATER,    GREATER_OR_EQUAL,LESS,LESS_OR_EQUAL,NOT_EQUAL,NO_OP}struct KeyCondition {      1: optional i32 offset,    2: optional i32 len,3: optional CompareType comp,4: optional string value}struct ColCondition {      1: optional string colName,      2: optional CompareType comp,3: optional string value}struct PageCondition {      1: optional i32 offset,    2: optional i32 limit}struct Conditions {      1: optional list keyCons,    2: optional list colCons,3: optional PageCondition pageCon} service BaseApiService {ReObject createTable(1:AppInfo app, 2:TableInfo info)ReObject addTableColumns(1:AppInfo app, 2:string tableName, 3:list colList)ReObject getTableInfo(1:AppInfo app, 2:string tableName)ReObject getAllTableInfo(1:AppInfo app)ReObject deleteTable(1:AppInfo app, 2:string tableName)ReObject getTableRows(1:AppInfo app, 2:string tableName, 3:list pks, 4:list colNames)ReObject getTableRowsByRange(1:AppInfo app, 2:string tableName, 3:string startPK, 4:string endPK, 5:list colNames)ReObject addTableRows(1:AppInfo app, 2:string tableName, 3:list rows)ReObject deleteTableRows(1:AppInfo app, 2:string tableName, 3:list pks)  }  service DevelopApiService {ReObject getTableRowsByPage(1:AppInfo app, 2:string tableName, 3:string startPK, 4:string endPK, 5:Conditions con, 6:list colNames)}

2、用cmd命令thrift-0.9.0.exe -r -gen java DevelopApiService.thrift生成java类

3、写实现类继承Iface接口

public class DevelopApiServiceImpl implements Iface {}

4、写服务端代码

package cn.cstor.cproc.java.serve;  import org.apache.log4j.Logger;  import org.apache.thrift.TProcessorFactory;  import org.apache.thrift.protocol.TCompactProtocol;  import org.apache.thrift.server.THsHaServer;  import org.apache.thrift.server.TServer;  import org.apache.thrift.transport.TFramedTransport;  import org.apache.thrift.transport.TNonblockingServerSocket;  import org.apache.thrift.transport.TTransportException;  import cn.cstor.cproc.java.impl.DevelopApiServiceImpl;import cn.cstor.cproc.java.thrift.DevelopApiService; public class DevelopServe {           private static final Logger logger = Logger.getLogger(DevelopServe.class);      private int port;     public DevelopServe(int port) {          this.port = port;      }      @SuppressWarnings("unchecked")      public void start() {          try {              TNonblockingServerSocket socket = new TNonblockingServerSocket(port);              final DevelopApiService.Processor processor = new DevelopApiService.Processor(                      new DevelopApiServiceImpl());              THsHaServer.Args arg = new THsHaServer.Args(socket);              // 高效率的、密集的二进制编码格式进行数据传输              // 使用非阻塞方式,按块的大小进行传输,类似于 Java 中的 NIO              arg.protocolFactory(new TCompactProtocol.Factory());              arg.transportFactory(new TFramedTransport.Factory());              arg.processorFactory(new TProcessorFactory(processor));              TServer server = new THsHaServer(arg);              logger.info("服务启动-使用:非阻塞&高效二进制编码");             System.out.println("DevelopServe start");            server.serve();          } catch (TTransportException e) {              e.printStackTrace();          } catch (Exception e) {              e.printStackTrace();          }      }  }  


5、客户端代码
package cn.cstor.cproc.java.serve;  import org.apache.thrift.TApplicationException;  import org.apache.thrift.TException;  import org.apache.thrift.protocol.TCompactProtocol;  import org.apache.thrift.protocol.TProtocol;  import org.apache.thrift.transport.TFramedTransport;  import org.apache.thrift.transport.TSocket;  import org.apache.thrift.transport.TTransport;  import org.apache.thrift.transport.TTransportException;  import cn.cstor.cproc.java.thrift.DevelopApiService;import cn.cstor.cproc.java.thrift.ReObject;   public class TestClient {      public final static int PORT = 9999;      public static final String address = "localhost";      public static final int clientTimeout = 30000;          public static void main(String[] args) {    TTransport transport = new TFramedTransport(new TSocket(address, PORT,                  clientTimeout));          TProtocol protocol = new TCompactProtocol(transport);          DevelopApiService.Client client = new DevelopApiService.Client(protocol);          try {              transport.open();              ReObject ro = client.getTableRowsByPage(null, null, null, null, null, null);            System.out.println(ro.getMsg());        } catch (TApplicationException e) {              System.out.println(e.getMessage() + " " + e.getType());          } catch (TTransportException e) {              e.printStackTrace();          } catch (TException e) {              e.printStackTrace();          }          transport.close();  }}


6、注:0.90版本之前不支持一个端口发布多个接口,从0.91开始服务器代码与单一接口的服务器代码最大的不同是使用了“TMultiplexedProcessor”类,通过该类,可以注册多个接口的服务实现类:

TMultiplexedProcessor processor = new TMultiplexedProcessor();    

       processor.registerProcessor("TopicService"newTopicService.Processor(newTopicImpl()));

    processor.registerProcessor("UserService"new UserService.Processor(newUserImpl()));

其他代码就跟以前的服务器代码一样了。

原创粉丝点击