转自:http://blog.csdn.net/lk10207160511/article/details/50450541
一、概述 Thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 等等编程语言间无缝结合的、高效的服务。 Thrift最初由facebook开发,07年四月开放源码,08年5月进入apache孵化器。thrift允许你定义一个简单的定义文件中的数据类型和服务接口。以作为输入文件,编译器生成代码用来方便地生成RPC客户端和服务器通信的无缝跨编程语言。【来自百度百科】 官网地址:thrift.apache.org 二、下载依赖(Maven) 1、在pom.xml 中添加如下内容: [html] view plain copy print? <span style="white-space:pre"> </span><dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.9.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> 三、基本概念以及实现步骤 1、数据传输协议 TBinaryProtocol : 二进制格式. TCompactProtocol : 压缩格式 TJSONProtocol : JSON格式 TSimpleJSONProtocol : 提供JSON只写协议, 生成的文件很容易通过脚本语言解析 注意:客户端和服务端的协议要一致。 2、服务端 实现服务处理接口impl 创建TProcessor 创建TServerTransport 创建TProtocol 创建TServer 启动Server 3、客户端 创建Transport 创建TProtocol 基于TTransport和TProtocol创建 Client 调用Client的相应方法 四、实例 1、thrift文件创建,并在文件中定义需要的接口方法 namespace java com.jmust.thrift.demo service HelloWorldService { string sayHello(1:string username) } 2、执行thrift-0.9.3.exe生成代码 thrift-0.9.3.exe -r -gen java ./demoHello.thrift 3、创建一个服务maven项目(shrift-service),将生成的HelloWorldService.java文件复制到自己的项目中,利用maven打包成为bundle作为一个服务包,里面代码具体是什么样子的,我们不需要关心,到时候需要用到的地方,只需要把这个服务包引进去即可使用,下面看看我的pom.xml文件(把该开放出去的package开放出去,该引进来的package引进来) [html] view plain copy print? <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jmust.thrift</groupId> <artifactId>thrift-service</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>thrift-service</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.9.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.4.3</version> <executions> <execution> <phase>compile</phase> </execution> </executions> <configuration> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.4</version> <executions> <execution> <phase>deploy</phase> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> <configuration> <skip>false</skip> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.10.3</version> <configuration> <aggregate>true</aggregate> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.7.2</version> <configuration> <skip>false</skip> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.7</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.3.1</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> </manifest> <manifestEntries> <Class-Path>.</Class-Path> <Built-By>JMUST</Built-By> <Bundle-ManifestVersion>2</Bundle-ManifestVersion> <Bundle-Name>${project.groupId}.${project.ArtifactId}</Bundle-Name> <Bundle-SymbolicName>${project.groupId}.${project.ArtifactId}</Bundle-SymbolicName> <Bundle-Version>${project.version}</Bundle-Version> <Bundle-Vendor>${project.groupId}</Bundle-Vendor> <Export-Package>com.jmust.thrift.service;version=${project.version} </Export-Package> <Import-Package> javax.annotation,org.slf4j,org.apache.thrift,org.apache.thrift.async,org.apache.thrift.scheme,org.apache.thrift.protocol,org.apache.thrift.server.AbstractNonblockingServer </Import-Package> </manifestEntries> </archive> </configuration> </plugin> </plugins> </build> </project> 4、再创建一个实现以上服务maven项目(thrift-demo),pom.xml文件只需要引入 [html] view plain copy print? <span style="white-space:pre"> </span><dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.9.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>com.jmust.thrift</groupId> <artifactId>thrift-service</artifactId> <version>1.0.0</version> </dependency> 4.1、实现接口Iface [java] view plain copy print? package com.jmust.thrift.impl; import org.apache.thrift.TException; import com.jmust.thrift.service.HelloWorldService.Iface; /** * * @author LK * */ public class HelloWorldImpl implements Iface { public HelloWorldImpl(){ } public String sayHello(String username) throws TException { return "Hi," + username + " welcome to my blog www.jmust.com"; } } 5、根据协议去实现服务端 5.1、TSimpleServer服务端-----简单的单线程服务模型,一般用于测试 [java] view plain copy print? package com.jmust.thrift.demo; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TServer.Args; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.transport.TServerSocket; import com.jmust.thrift.impl.HelloWorldImpl; import com.jmust.thrift.service.HelloWorldService.Iface; import com.jmust.thrift.service.HelloWorldService.Processor; /** * 单线程服务模型,一般用于测试 TSimpleServer服务端 * @author LK * */ public class HelloTSimpleServerDemo { public static final int SERVER_PORT = 8090; public void startServer() { try { System.out.println("HelloWorld TSimpleServer start ...."); TProcessor tprocessor = new Processor<Iface>( new HelloWorldImpl()); // 简单的单线程服务模型,一般用于测试 TServerSocket serverTransport = new TServerSocket(SERVER_PORT); Args tArgs = new 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) { HelloTSimpleServerDemo server = new HelloTSimpleServerDemo(); server.startServer(); } } 5.2、TThreadPoolServer 服务模型 ------线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求 [java] view plain copy print? package com.jmust.thrift.demo; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.server.TThreadPoolServer.Args; import org.apache.thrift.transport.TServerSocket; import com.jmust.thrift.impl.HelloWorldImpl; import com.jmust.thrift.service.HelloWorldService.Iface; import com.jmust.thrift.service.HelloWorldService.Processor; /** * 线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求 TThreadPoolServer 服务模型 * @author LK * */ public class HelloTThreadPoolServerDemo { public static final int SERVER_PORT = 8090; public void startServer() { try { System.out.println("HelloWorld TThreadPoolServer start ...."); TProcessor tprocessor = new Processor<Iface>( new HelloWorldImpl()); TServerSocket serverTransport = new TServerSocket(SERVER_PORT); //TThreadPoolServer 线程池服务模型 Args ttpsArgs = new Args( serverTransport); ttpsArgs.processor(tprocessor); ttpsArgs.protocolFactory(new TBinaryProtocol.Factory()); //线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。 TServer server = new TThreadPoolServer(ttpsArgs); server.serve(); } catch (Exception e) { System.out.println("Server start error!!!"); e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { HelloTThreadPoolServerDemo server = new HelloTThreadPoolServerDemo(); server.startServer(); } } 5.3、TNonblockingServer 服务模型 -------使用非阻塞式IO,服务端和客户端需要指定 TFramedTransport 数据传输的方式 [java] view plain copy print? package com.jmust.thrift.demo; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.server.TNonblockingServer; import org.apache.thrift.server.TNonblockingServer.Args; import org.apache.thrift.server.TServer; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TNonblockingServerSocket; import com.jmust.thrift.impl.HelloWorldImpl; import com.jmust.thrift.service.HelloWorldService.Iface; import com.jmust.thrift.service.HelloWorldService.Processor; /** * 使用非阻塞式IO,服务端和客户端需要指定 TFramedTransport 数据传输的方式 TNonblockingServer 服务模型 * @author LK * */ public class HelloTNonblockingServerDemo { public static final int SERVER_PORT = 8090; public void startServer() { try { System.out.println("HelloWorld TNonblockingServer start ...."); TProcessor tprocessor = new Processor<Iface>( new HelloWorldImpl()); TNonblockingServerSocket tnbSocketTransport = new TNonblockingServerSocket(SERVER_PORT); Args tnbArgs = new Args(tnbSocketTransport); tnbArgs.processor(tprocessor); tnbArgs.transportFactory(new TFramedTransport.Factory()); tnbArgs.protocolFactory(new TCompactProtocol.Factory()); TServer server = new TNonblockingServer(tnbArgs); server.serve(); } catch (Exception e) { System.out.println("Server start error!!!"); e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { HelloTNonblockingServerDemo server = new HelloTNonblockingServerDemo(); server.startServer(); } } 5.4、THsHaServer服务模型 -------半同步半异步的服务端模型,需要指定为: TFramedTransport 数据传输的方式 [java] view plain copy print? package com.jmust.thrift.demo; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.THsHaServer; import org.apache.thrift.server.THsHaServer.Args; import org.apache.thrift.server.TServer; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TNonblockingServerSocket; import com.jmust.thrift.impl.HelloWorldImpl; import com.jmust.thrift.service.HelloWorldService.Iface; import com.jmust.thrift.service.HelloWorldService.Processor; /** * 半同步半异步的服务端模型,需要指定为: TFramedTransport 数据传输的方式 THsHaServer服务模型 * @author LK * */ public class HelloTHsHaServerDemo { public static final int SERVER_PORT = 8090; public void startServer() { try { System.out.println("HelloWorld THsHaServer start ...."); TProcessor tprocessor = new Processor<Iface>( new HelloWorldImpl()); TNonblockingServerSocket tnbSocketTransport = new TNonblockingServerSocket(SERVER_PORT); Args args = new Args(tnbSocketTransport); args.processor(tprocessor); args.transportFactory(new TFramedTransport.Factory()); args.protocolFactory(new TBinaryProtocol.Factory()); TServer server = new THsHaServer(args); server.serve(); } catch (Exception e) { System.out.println("Server start error!!!"); e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { HelloTHsHaServerDemo server = new HelloTHsHaServerDemo(); server.startServer(); } } 6、客户端实现 6.1、同步 [java] view plain copy print? package com.jmust.thrift.demo; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; 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 com.jmust.thrift.service.HelloWorldService.Client; /** * * @author LK * */ public class HelloClientDemo { public static final String SERVER_IP = "localhost"; public static final int SERVER_PORT = 8090; public static final int TIMEOUT = 30000; /** * * @param userName */ public void startClient(String userName) { TTransport transport = null; try { //transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT); transport = new TFramedTransport(new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT)); // 协议要和服务端一致 TProtocol protocol = new TBinaryProtocol(transport); //TProtocol protocol = new TCompactProtocol(transport); // TProtocol protocol = new TJSONProtocol(transport); Client client = new Client(protocol); transport.open(); String result = client.sayHello(userName); System.out.println("Thrify client result =: " + result); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } finally { if (null != transport) { transport.close(); } } } /** * @param args */ public static void main(String[] args) { HelloClientDemo client = new HelloClientDemo(); client.startClient("lvk"); } } 6.2、异步 [html] view plain copy print? package com.jmust.thrift.demo; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.async.TAsyncClientManager; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TNonblockingSocket; import org.apache.thrift.transport.TNonblockingTransport; import com.jmust.thrift.service.HelloWorldService.AsyncClient; import com.jmust.thrift.service.HelloWorldService.AsyncClient.sayHello_call; /** * 异步客户端 * @author LK * */ public class HelloAsynClientDemo { public static final String SERVER_IP = "localhost"; public static final int SERVER_PORT = 8090; public static final int TIMEOUT = 30000; /** * * @param userName */ public void startClient(String userName) { try { TAsyncClientManager clientManager = new TAsyncClientManager(); TNonblockingTransport transport = new TNonblockingSocket(SERVER_IP, SERVER_PORT, TIMEOUT); TProtocolFactory tprotocol = new TCompactProtocol.Factory(); AsyncClient asyncClient = new AsyncClient(tprotocol, clientManager, transport); System.out.println("Client start ....."); CountDownLatch latch = new CountDownLatch(1); AsynCallback callBack = new AsynCallback(latch); System.out.println("call method sayHello start ..."); asyncClient.sayHello(userName, callBack); System.out.println("call method sayHello .... end"); boolean wait = latch.await(30, TimeUnit.SECONDS); System.out.println("latch.await =:" + wait); } catch (Exception e) { e.printStackTrace(); } System.out.println("startClient end."); } public class AsynCallback implements AsyncMethodCallback<sayHello_call>{ private CountDownLatch latch; public AsynCallback(CountDownLatch latch) { this.latch = latch; } public void onComplete(sayHello_call response) { System.out.println("onComplete"); try { // Thread.sleep(1000L * 1); System.out.println("AsynCall result =:" + response.getResult().toString()); } catch (TException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } public void onError(Exception exception) { System.out.println("onError :" + exception.getMessage()); latch.countDown(); } } /** * @param args */ public static void main(String[] args) { HelloAsynClientDemo client = new HelloAsynClientDemo(); client.startClient("lvk"); } } 7.、测试步骤 先运行服务端,让后再运行客户端,看看是否输出预计结果。
相关推荐
在本示例中,我们将探讨如何使用 Thrift 的 Java 实现,以及提供的 Thrift0.9.1 版本的示例代码。 Thrift 的核心思想是通过定义一种中间表示(IDL,接口定义语言)来描述服务和数据类型。这些 IDL 文件被编译成各种...
在本示例中,我们将深入探讨Thrift的使用,通过具体的代码示例来帮助理解其工作原理。 首先,Thrift的使用流程通常包括以下几个步骤: 1. **定义服务接口**:在Thrift IDL(Interface Description Language)文件...
在这个“C++(Qt)下的thrift的使用示例”中,我们将探讨如何在Qt项目中集成和使用Thrift。 首先,Thrift的主要功能是定义服务接口和数据结构,这些定义会被编译成各种目标语言的代码,以便于实现客户端和服务器端...
通过这些示例,你可以更好地理解如何在实际项目中整合Java、Thrift2和HBase,以实现高效的数据存取。记住,实践是检验理论的最好方法,所以尝试运行这些示例,根据需求进行调整,你会发现自己的技能会得到显著提升。
以下是一个简单的ThriftServlet示例: ```java public class ThriftServlet extends HttpServlet { private final TProcessor processor; public ThriftServlet(MyService.Processor processor) { this....
本示例将详细阐述如何使用Java操作Thrift。 首先,让我们了解Thrift的基本流程: 1. **定义服务**:使用Thrift的IDL编写服务接口。例如,创建一个名为`service.thrift`的文件,定义一个简单的服务: ```thrift ...
本示例主要探讨如何在Java环境中使用Thrift实现RPC。 首先,我们需要理解Thrift的工作原理。Thrift通过定义一种中间表示(IDL,Interface Description Language)来描述服务接口和数据结构。这个IDL文件类似于接口...
在本示例中,我们关注的是Thrift的“多接口服务”功能。 在传统的Thrift服务中,一个服务通常只包含一组相关的操作(即方法)。然而,在实际项目中,有时我们需要将不同的功能逻辑拆分为多个独立的服务接口,以便更...
此文件为自己在Mac电脑上写的thrift的demo,使用maven 管理了小程序,并用thrift生成了源码,其中对thrift生成的源码,把override注销了,其他的没处理,如果感兴趣参考博客:...
在"thrift框架示例"中,我们关注的是如何使用Thrift在客户端和服务器端之间建立通信。Thrift的流程通常包括以下几个步骤: 1. **定义服务接口**:首先,我们需要使用Thrift IDL编写服务接口定义文件,例如`service....
将 Spring 与 Thrift 集成,可以利用 Spring 的强大功能来管理和调度 Thrift 服务,同时借助 Thrift 实现高效的数据传输和跨语言服务调用。 集成 Spring 和 Thrift 主要涉及以下几个步骤: 1. **创建 Thrift IDL ...
压缩包中的`thrift-0.8.0.tar.gz`可能是旧版本的Thrift源码或者编译器,`ThriftCSharp.rar`和`csharp.rar`可能包含额外的C#相关的Thrift示例或库,而`thriftTest.zip`可能是测试项目或样例代码。如果你需要更详细的...
`ThriftHelloClient`可能是一个简单的Thrift客户端示例,展示了如何调用Thrift服务的方法。 在学习这个实例时,你需要理解Thrift的IDL语法,如何使用Thrift编译器生成代码,以及如何在Java环境中集成和使用Thrift库...
从 iOS 应用程序访问 API 的示例。 构建接口 每当您更改 Thrift 接口定义时,您都需要为您使用的语言更新生成的代码。 在我们的例子中,我们想要构建 NodeJS 和 Cocoa 绑定: thrift -o client/ThriftTest --gen ...
在实践中,`thrift-demo`可能是一个包含Thrift示例代码的压缩包,包括`.thrift`文件、生成的客户端和服务端代码以及运行示例所需的配置和脚本。通过学习和运行这个示例,你可以更好地理解Thrift的工作原理,并掌握...
在 "thrift-demo" 中,我们可以找到一个简单的 Thrift 示例,它可能包括以下部分: - 服务定义的 IDL 文件(如 `helloworld.thrift`) - 编译后的服务接口和数据结构代码(如 `helloworld.py` 或 `helloworld....
在本示例中,我们将探讨如何使用Thrift在Java和Python之间实现RPC(Remote Procedure Call)的互相调用。 首先,我们需要了解Thrift IDL。在Thrift IDL文件中,我们可以定义服务接口、数据结构(如struct)和常量。...
为了验证 Thrift 是否正确安装,可以在 `thrift-xx.xx.xx/tutorial` 目录下运行自带的示例。对于 C++ 示例,需要使用 `thrift` 工具生成 C++ 代码,然后编译生成的 `CppServer` 和 `CppClient`,分别运行这两个程序...
在压缩包中,"QT使用Thrift样例"应该包含了完整的代码示例,包括QT工程文件、Thrift服务定义文件、以及如何集成Boost的示例。通过学习和分析这个样例,开发者可以快速掌握在Windows环境下使用QT、Thrift和Boost进行...
在Thrift示例中,可能会有处理字符串、网络连接或者其他辅助任务的工具类。 在实际开发中,这个"thrift example"可能包括了以下步骤: 1. 使用Thrift IDL编写服务接口定义。 2. 使用Thrift编译器生成对应编程语言的...