一.什么是RPC?

RPC(Remote Procedure Call Protocol)——远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。

RPC协议假定某些传输协议的存在,如TCP或UDP,为通信程序之间携带信息数据。在OSI网络通信模型中,RPC跨越了传输层和应用层。RPC使得开发包括网络分布式多程序在内的应用程序更加容易。

二.什么是Thrift?

thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 这些编程语言间无缝结合的、高效的服务。

thrift最初由facebook开发,07年四月开放源码,08年5月进入apache孵化器。

三.下载,安装,配置Thrift

本机环境:ubuntu 12.04 (64bit)

1.下载:

2.安装,配置Thrift

Building from source

First make sure your system meets all necessary Apache Thrift Requirements

If you are building from the first time out of the source repository, you will need to generate the configure scripts. (This is not necessary if you downloaded areleased tarball.) From the top directory, do:

./bootstrap.sh

Once the configure scripts are generated, thrift can be configured. From the top directory, do:

./configure

Disable a language:

./configure --without-java

You may need to specify the location of the boost files explicitly. If you installed boost in /usr/local, you would run configure as follows:

./configure --with-boost=/usr/local

If you want to override the logic of the detection of the Java SDK, use the JAVAC environment variable:

./configure JAVAC=/usb/bin/javac

Note that by default the thrift C++ library is typically built with debugging symbols included. If you want to customize these options you should use the CXXFLAGS option in configure, as such:

./configure CXXFLAGS='-g -O2'./configure CFLAGS='-g -O2'./configure CPPFLAGS='-DDEBUG_MY_FEATURE'

To see other configuration options run

./configure --help

Once you have run configure you can build Thrift via make:

make

and run the test suite:

make check

and the cross language test suite:

sh test/test.sh

Issues while compiling

"compiler/cpp/thriftl.cc:2190: undefined reference to `yywrap'"

you need to install the Flex library (See also Apache Thrift Requirements ) and re-run the configuration script.

mv: cannot stat "'.deps/TBinaryProtocol.Tpo': No such file or directory" while building the Thrift Runtime Library

Re-reun configure with

--enable-libtool-lock

or by turning off parallel make by placing.NOTPARALLEL:in lib/cpp/Makefile or

make -j 1

Although the thrift compiler build appears to be compatible with parallel make without libtool lock, the thrift runtime build is not.

Installing

From the top directory, become superuser and do:

make install

Note that some language packages must be installed manually using build tools better suited to those languages (this applies to Java, Ruby, PHP).

Look for the README file in the lib// folder for more details on the installation of each language library package.

总结下来,第1步,先解压thrift-0.9.1.tar.gz,解压命令:

tar -xvf thrift-0.9.1.tar.gz

第2步,输入以下命令:

$cd thrift-0.9.1$./configure

$make#sudo make install

关于配置的问题可以查看命令:

./configure --help

可以关闭你不熟悉的语言,因为thrift支持的语言非常多,可以关闭一些用不到的,如python,gt4等;

关闭命令为:

./configure --without-qt4

在install的过程中如果报一些test方面的error可以忽略.

上面的步骤走完以后,可以在任意一个目录下输入如下命令进行测试:

amosli@amosli-pc:~/workspace$ thrift -version

Thrift version0.9.1

四.Thrift基本概念

1.数据类型

基本类型:

bool:布尔值,true 或 false,对应 Java 的 boolean

byte:8 位有符号整数,对应 Java 的 byte

i16:16 位有符号整数,对应 Java 的 short

i32:32 位有符号整数,对应 Java 的 int

i64:64 位有符号整数,对应 Java 的 long

double:64 位浮点数,对应 Java 的 double

string:utf-8编码的字符串,对应 Java 的 String

结构体类型:

struct:定义公共的对象,类似于 C 语言中的结构体定义,在 Java 中是一个 JavaBean

容器类型:

list:对应 Java 的 ArrayList

set:对应 Java 的 HashSet

map:对应 Java 的 HashMap

异常类型:

exception:对应 Java 的 Exception

服务类型:

service:对应服务的类

2.服务端编码基本步骤:

实现服务处理接口impl

创建TProcessor

创建TServerTransport

创建TProtocol

创建TServer

启动Server

3.客户端编码基本步骤:

创建Transport

创建TProtocol

基于TTransport和TProtocol创建 Client

调用Client的相应方法

4.数据传输协议

TBinaryProtocol : 二进制格式.

TCompactProtocol : 压缩格式

TJSONProtocol : JSON格式

TSimpleJSONProtocol : 提供JSON只写协议, 生成的文件很容易通过脚本语言解析

tips:客户端和服务端的协议要一致

五.Java实例

1.引入jar包

我这里用到的是maven进行管理jar包的,所以首先新建一个maven项目,然后在pom.xml中添加如下内容:

org.apache.thrift

libthrift

0.9.1

org.slf4j

slf4j-log4j12

1.5.8

2.创建Thrift文件

创建Thrift文件:amosli@amosli-pc:/media/f91a4cca-0b96-4c30-b140-7918a196de3e/amosli/java/rpc/DemoTest/demoHello.thrift ,内容如下:

namespace java com.amos.thrift.demo

service HelloWorldService {

string sayHello(1:string username)

}

3.生成java文件:

thrift -r -gen java demoHello.thrift

文件目录如下:

$ tree

.

├── demoHello.thrift

└── gen-java

└── com

└── amos

└── thrift

└── demo

└── HelloWorldService.java

把生成的HelloWorldService.java文件拷贝到项目中去.

4.实现接口Iface

packagecom.amos;/*** Created by amosli on 14-8-12.*/

public class HelloWorldImpl implementsHelloWorldService.Iface {publicHelloWorldImpl() {

}

@OverridepublicString sayHello(String username) {return "Hi," + username + " ,Welcome to the thrift's world !";

}

}

5.TSimpleServer服务端

简单的单线程服务模型,一般用于测试。

编写服务端server代码:HelloServerDemo.java

packagecom.amos;importorg.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.protocol.TCompactProtocol;importorg.apache.thrift.server.TServer;importorg.apache.thrift.server.TSimpleServer;importorg.apache.thrift.transport.TServerSocket;/*** Created by amosli on 14-8-12.*/

public classHelloServerDemo {public static final int SERVER_PORT = 8090;/***@paramargs*/

public static voidmain(String[] args) {

HelloServerDemo server= newHelloServerDemo();

server.startServer();

}public voidstartServer() {try{

System.out.println("HelloWorld TSimpleServer start ....");//TProcessor tprocessor = new HelloWorldService.Processor(new HelloWorldImpl());

HelloWorldService.Processor tprocessor = new HelloWorldService.Processor(newHelloWorldImpl());//简单的单线程服务模型,一般用于测试

TServerSocket serverTransport = newTServerSocket(SERVER_PORT);

TServer.Args tArgs= newTServer.Args(serverTransport);

tArgs.processor(tprocessor);//tArgs.protocolFactory(new TBinaryProtocol.Factory());

tArgs.protocolFactory(newTCompactProtocol.Factory());//tArgs.protocolFactory(new TJSONProtocol.Factory());

TServer server = newTSimpleServer(tArgs);

server.serve();

}catch(Exception e) {

System.out.println("Server start error!!!");

e.printStackTrace();

}

}

}

6.编写客户端代码

packagecom.amos;importorg.apache.thrift.TException;importorg.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.protocol.TCompactProtocol;importorg.apache.thrift.protocol.TProtocol;importorg.apache.thrift.transport.TSocket;importorg.apache.thrift.transport.TTransport;importorg.apache.thrift.transport.TTransportException;/*** Created by amosli on 14-8-12.*/

public classHelloClientDemo {public static final String SERVER_IP = "localhost";public static final int SERVER_PORT = 8090;public static final int TIMEOUT = 30000;/***@paramargs*/

public static voidmain(String[] args) {

HelloClientDemo client= newHelloClientDemo();

client.startClient("amosli");

}/***@paramuserName*/

public voidstartClient(String userName) {

TTransport transport= null;try{

transport= newTSocket(SERVER_IP, SERVER_PORT, TIMEOUT);//协议要和服务端一致//TProtocol protocol = new TBinaryProtocol(transport);

TProtocol protocol = newTCompactProtocol(transport);//TProtocol protocol = new TJSONProtocol(transport);

HelloWorldService.Client client = newHelloWorldService.Client(

protocol);

transport.open();

String result=client.sayHello(userName);

System.out.println("Thrift client result =: " +result);

}catch(TTransportException e) {

e.printStackTrace();

}catch(TException e) {

e.printStackTrace();

}finally{if (null !=transport) {

transport.close();

}

}

}

}

项目最终结构图:

7.最终运行效果

服务端:

客户端:

参考:

1.http://baike.baidu.com/view/1698865.htm?fr=aladdin

2.http://thrift.apache.org/docs/BuildingFromSource

3.http://www.micmiu.com/soa/rpc/thrift-sample/

4.http://blog.chinaunix.net/uid-20357359-id-2876170.html

5.http://baike.baidu.com/view/7287257.htm?fromtitle=RPC&fr=aladdin

java thrift 教程_RPC学习----Thrift快速入门和Java简单示例相关推荐

  1. MongoDB学习(五)使用Java驱动程序3.3操作MongoDB快速入门

    [引言] 毕竟现在MongoDB还是出于成长阶段,所以现在网上相关的资料很少,而且大部分还都是针对于MongoDB的老版本的.再加上MongoDB的频繁升级.重大更新等等,导致菜鸟学习的难度增大. 好 ...

  2. Java 图片处理解决方案:ImageMagick 快速入门教程

    Java 图片处理解决方案:ImageMagick 快速入门教程 参考文章: (1)Java 图片处理解决方案:ImageMagick 快速入门教程 (2)https://www.cnblogs.co ...

  3. java akka 教程_快速入门 Akka Java 指南

    快速入门 Akka Java 指南 Akka 是一个用于在 JVM 上构建高并发.分布式和容错的事件驱动应用程序的运行时工具包.Akka 既可以用于 Java,也可以用于 Scala.本指南通过描述 ...

  4. Java如何快速入门?Java初学者从入门到精通必看!

            作为刚刚接触Java的小白来说,最担心的应该就是Java怎么学,都需要掌握哪些内容?今天这篇文章希望能帮助大家快速入门Java,少走弯路! 如何快速入门Java? 一.作为刚接触Jav ...

  5. 深度学习工程应用快速入门

    课程介绍 伴随人工智能时代的到来,深度学习技术也发挥着越来越重要作用,越来越多的技术人才开始投身入这一行业中,并希望发展成为一名深度学习算法工程师.然而,在实际的工程设计中,深度学习研发者总会面临着各 ...

  6. PR软件入门教程 Adobe Premiere Pro 快速入门指南

    原文(包含图片)链接:https://www.prjianji.com/1.html 了解如何开始使用面向电影制作人.电视节目制作人.新闻记者.学生和视频制作人员的非线性编辑软件 Premiere P ...

  7. HTML5+app开发学习之快速入门篇

    HTML5+app开发学习之快速入门篇 5+app开发概念理解相关 开发环境与支持 快速入门实战 5+app开发概念理解相关 见博文:学习跨平台移动应用开发必须理解的一些概念 开发环境与支持 开发环境 ...

  8. Spring学习(1)——快速入门

    Spring学习(1)--快速入门 认识 Spring 框架 Spring 框架是 Java 应用最广的框架,它的成功来源于理念,而不是技术本身,它的理念包括 IoC (Inversion of Co ...

  9. STL教程:C++ STL快速入门

    目录 1.STL引言 2.STL是什么(STL简介) 3.STL历史 4.STL组件 5.STL基本结构 6.STL 使用方法 7.STL目录 网址:STL教程:C++ STL快速入门(非常详细) 第 ...

  10. unformat方法java_快速入门介绍Java中强大的String.format()

    快速入门介绍Java中强大的String.format() 发布于 2020-12-12| 复制链接 摘记: 前言从 Java 5.0 开始,String 类新增了一个强大的字符串格式化方法 form ...

最新文章

  1. NP-Hard问题及组合最优化问题
  2. java主键后四位顺序号_JAVA中取顺序号 (转)
  3. html的学习小结(3):HTML 4.0 事件属性
  4. 算法设计与分析python_Python算法设计与分析
  5. mysql语法学习(一)__Instances__表
  6. CSS3那些不为人知的高级属性
  7. 汇编中各寄存器的作用(16位CPU14个,32位CPU16个)和 x86汇编指令集大全(带注释)
  8. Oracle优化查询技巧
  9. vscode 不展示文档注释内容_文本框这样用,实现文档不同板块内容高效联动,你还不知道吧...
  10. 华为机试HJ73:计算日期到天数转换
  11. 解决:configure: error: Missing Xext.h, maybe to install libxext-dev packages?
  12. Python开胃菜(1):搭建开发环境
  13. image target behaviour 和image target的关系_图片分析软件Image-Pro Plus的基础操作
  14. 计算机视觉论文-2021-06-02
  15. 宝塔面板+腾讯云轻量应用服务器部署fiora聊天室
  16. 怎么把PicPick设置成中文版?
  17. 游戏创业团队的技术选型之Flash AIR
  18. 【SQL】CAST()函数,(CAST AS decimal)
  19. TCP协议 握手与挥手
  20. 心理测评软件php mysql_心理测评系统

热门文章

  1. Cobal Strike免杀过360
  2. python代码实现自动登录
  3. html个人网页完整代码模板,静态 html 个人主页 模板
  4. 子龙山人:我从Cocos2d-x团队里学到的
  5. 创建MSN界面式的Ext JS布局
  6. 软件开发模型有哪些?
  7. 计算机软件测试方法的分析,计算机软件测试方法的分析.doc
  8. 利用Windows自带的Certutil查看文件MD5
  9. lcd4linux 支持的相框,最新版AIDA64支持LCD4WIN相框太给力了(20140826更新啦)!
  10. 斯坦福李飞飞教授:人口普查不用上门,谷歌街景加深度学习就搞定