微信里微信里面的摩拜单车车是全国通用的吗

Thrift协议分为数层。以下逐层分析其源代码。
一、传输层
& & 传输层在其transport文件夹中。
& & TTransport.php中定义了TTransport类,这是是transport文件夹下所有具体类的基类。TTransport类定义了以下几个基本操作:
流是否打开打开流关闭流读一定数量的字节保证读一定数量字节(TTransport类中唯一的非抽象函数,利用上一个函数循环读取,一定保证读到指定数量的字节)写出刷新流
& & 所有子类以不同方法定义了这些函数。子类中,有的定义完全,有的还有transport_字段(一个TTransport类对象),依靠transport_字段来实现操作。这说明所有的子类又可以分为两大类:底层的、定义完全的类,和上层的,依靠底层类才能工作的类。
& & 定义完全的类有:
TSocket。读写、刷新socket。THttpClient。通过HTTP资源读取,写入缓冲区,刷新时将缓冲区内的字节全部写出。TPhpStream。读写php://input和php://output。TMemoryBuffer。简单地读写一块内存。TNullTransport类。所有函数的定义都为空或者直接抛出异常,文件中写明“这个类只是用作测量结构体的size”。
& & 定义不完全的类有:
TBufferedTransport。其中有一块内存作为读缓冲区,一块内存作为写缓冲区。读写的时候实际只是在操作这两块缓冲区,知道读缓冲区中的字节不够本次读取,或者写缓冲区超过规定的大小,或者刷新流是,才利用其transport_字段进行实际的读写操作。TFramedTransport。其中也有一块读缓冲区,一块写缓冲区,一个读控制位,一个写控制位。开启读写控制时,每次读会读一整帧(先读帧头,解析出要读取多少字节,读取这些字节),写时先写到写缓冲区,刷新时先写帧头指明字节数量,再写数据。如果不开两个控制位,则使用期transport_字段直接进行读写操作。
二、协议层
& & 协议层相关内容在protocol文件夹中。
& & TProtocol类是protocol文件夹下所有类的基类,其内部有一个TTransport对象的字段,用作通信动作。另外定义了较多的抽象函数:
消息相关:(read/write)Message(Begin/End) 用来开始/结束读写消息。看参数,要远程调用的函数名作为一个参数被传递过去;消息分为两种:调用和回复。复杂的结构:读写Struct, Fields, Map, List, Set的Begin/End函数。消息和复杂结构可能需要标明开始与结束,因此需要Begin/End函数。简单的结构:Bool, Byte, 数,字符串的读写函数。简单类型就不分Begin/End函数了。
& & 还有以下两个非抽象函数:
skip函数。接受一个类型作为参数,然后调用以上的函数得到该类型的一个值。skipBinary函数。接受一个TTransport对象和一个类型作为参数,从TTransport取出与类型长度一样的字节(不包括类型头部的知识信息)。
& &&TBinaryProtocol类提供了该抽象协议的一种实现。读和写都是通过内部的TTransport对象的字段进行。使用pack和unpack函数,将不同的类型编成不同的字节流,然后读写。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:874次
排名:千里之外转载请指明出处:&
thrift 是什么东西,就不多说了 ,网上都有。
现在展示我做的API。
1. 安装thrift 后开始写代码。
  环境:
& & &&Linux version 2.6.18;
  Thrift version 0.9.3;
& & & PHP 5.5.9 ;
& & &&Python 2.4.3;
& & &部署:
& & &server 端使用 php,
& & &client &端使用 php,
& & &端口监控使用 python,
  目录结构:
2. &展示代码:
& & &创建 thrift 文件。
& & &说明:准备使用thrift实现一个获取图片信息的API,这里展示调通的结果。
& & 下面是 thrift 文件 ,文件名:&imginfo.thrift
1 namespace php Img
3 service ImgInfo{
string getimgInfo(1: string url),
2. 生成文件thrift文件中间接口文件
thrift -r --gen php:server imginfo.thrift
  官网上面没有添加server参数。我添加sever并测试通过,官网的方法本人没有测试。
  会在&imginfo.thrift 的目录生成一个 gen-php 目录,采用不同的语言会生成不同的目录
3. 编写客户端(client)程序
  在imginfo.thrift 目录层 创建php目录 &用于存放 客户端脚本。
  文件名:c.php
3 namespace Img\
4 # 红色是需要根据自己的实际情况修改目录的点
5 error_reporting(E_ALL);
7 require_once '/root/tools/thrift-0.9.3/lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php';
9 use Thrift\ClassLoader\ThriftClassL
11 $GEN_DIR = realpath(dirname(__FILE__) . '/../') . '/gen-php';
12 $loader = new ThriftClassLoader();
13 $loader-&registerNamespace('Thrift', '/root/tools/thrift-0.9.3/lib/php/lib');
14 $loader-&registerDefinition('Img', $GEN_DIR);
15 $loader-&register();
18 use Thrift\Protocol\TBinaryP
19 use Thrift\Transport\TS
20 use Thrift\Transport\THttpC
21 use Thrift\Transport\TBufferedT
22 use Thrift\Exception\TE
if (array_search('--http', $argv)) {
$socket = new THttpClient('localhost', 8080, '/php/s.php'); // 实际的server文件地址
$socket = new TSocket('localhost', 8080);
$transport = new TBufferedTransport($socket, );
$protocol = new TBinaryProtocol($transport);
$client = new \Img\ImgInfoClient($protocol);
$transport-&open();
35 #[ start 根据自己的文件调用就行
]#################################################
$ret = $client-&getimgInfo('BBBBBBBBBBBBBBBBBBBB');
echo $ret;
echo "&br /& \r\n";
40 #[ end ]#################################################
$transport-&close();
43 } catch (TException $tx) {
print 'TException: ' . $tx-&getMessage() . "\n";
4. 编写服务端(server)端
&  文件名:s.php ;也放在了php目录下。
  需要注意的点 &我用红色标识
3 namespace Img\
5 error_reporting(E_ALL);
7 require_once '/root/tools/thrift-0.9.3/lib/php/lib/Thrift/ClassLoader/ThriftClassLoader.php';
9 use Thrift\ClassLoader\ThriftClassL
11 $GEN_DIR = realpath(dirname(__FILE__).'/../').'/gen-php';
13 $loader = new ThriftClassLoader();
14 $loader-&registerNamespace('Thrift', '/root/tools/thrift-0.9.3/lib/php/lib');
15 $loader-&registerDefinition('Img', $GEN_DIR);
16 $loader-&register();
17 if (php_sapi_name() == 'cli') {
ini_set("display_errors", "stderr");
21 use Thrift\Protocol\TBinaryP
22 use Thrift\Transport\TPhpS
23 use Thrift\Transport\TBufferedT
25 class ImgInfoHandler implements \Img\ImgInfoIf {
protected $log = array();
# 编写自己个功能吧
public function getimgInfo($name) {
return $name . &' ==& &&client Request server is ok!';
34 header('Content-Type', 'application/x-thrift');
35 if (php_sapi_name() == 'cli') {
echo "\r\n";
39 $handler = new \Img\php\ImgInfoHandler();
40 $processor = new \Img\ImgInfoProcessor($handler);
42 $transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W));
43 $protocol = new TBinaryProtocol($transport, true, true);
45 $transport-&open();
46 $processor-&process($protocol, $protocol);
47 $transport-&close();
4. 编写端口监控代码。
  使用python,用于监控指定端口的http请求并交给s.php 处理
& & &需要注意的使用红色标识
1 #!/usr/bin/env python
5 import os
6 import BaseHTTPServer
7 import CGIHTTPServer
9 # chdir(2) into the tutorial directory.
10 os.chdir(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
11 # 指定目录 ,如果目录错误 请求会失败
12 class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories
= ['/php']
16 BaseHTTPServer.HTTPServer(('', 8080), Handler).serve_forever()
注意: client端请求server的脚本地址 需要和这里的保持一致。
& &1) 开启监控
python r.py
& &2)c 端请求 s 端
[root@localhost php]# php c.php --http
BBBBBBBBBBBBBBBBBBBB ==&
client Request server is ok!&br /&
 3)python 监控结果展示
[root@localhost php]# python r.py
localhost.localdomain - - [22/Oct/2015 02:36:34] "POST /php/s.php HTTP/1.0" 200 -
完成,希望对大家有帮助。
转载请指明出处:&
阅读(...) 评论()Thrift初步了解 - 真相也就如此 - ITeye技术网站
博客分类:
Thrift是一个可伸缩的跨语言的服务开发框架,对它的介绍就不google再复制了。当我们在做web开发时,前端可能采用php,python,ruby等脚本语言做用户的交互页面,那业务和数据库的部分不少就用Java来开发了,毕竟做Java开发的程序员的数量还是占大多数的。这时,我们网站或系统的架构就可以页面用php写,业务程序用Java来写(对web开发都熟悉的mvc来说,就是把controller层和service、dao层分开,用不同的语言来写),那不同语言之间的数据交互怎么实现呢(php如何调用java的一个service的方法)?webservice,thrift,avro等框架和技术就可以拿来使用了~好,直接写demo示例(thrift所用版本为0.9.1):
一、Javathrift接口定义文件:UserService.thrift
namespace php tService
namespace java tService
service UserService {
string getUserNameById(1:i32 userId);
server代码:ServerDemo.java
public class ServerDemo {
public static void main(String[] args) {
UserService.Processor processor = new UserService.Processor(new UserServiceImpl());
TServerTransport transport = new TServerSocket(9090);
TServer server = new TSimpleServer(new TServer.Args(transport).processor(processor));
System.out.println("Starting the simple server...");
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
client代码:ClientDemo.java
public class ClientDemo {
public static void main(String[] args) {
TTransport transport = new TSocket("localhost", 9090);
TProtocol protocol = new TBinaryProtocol(transport);
UserService.Client client = new UserService.Client(protocol);
transport.open();
System.out.println(client.getUserNameById(24));
transport.close();
} catch (Exception e) {
e.printStackTrace();
定义的thrift接口文件,通过`thrift --gen java UserService.thrift`就可以得到java的接口类,在windows下运行“thrift.exe"可执行文件。thrift的安装文件,到官网下载然后安装。
在下载的thrift-0.9.1.tar.gz包下的tutorial文件夹下有各种常用语言的demo例子,拿来学习是很不错的资料。在java的例子中除了SimpleServer的例子还有一个secure的例子。
client代码:ClientDemo.php
error_reporting(E_ALL);
require_once __DIR__ . "/thrift/lib/Thrift/ClassLoader/ThriftClassLoader.php";
use Thrift\ClassLoader\ThriftClassL
$GEN_DIR = realpath(dirname(__FILE__) . "/gen-php");
$loader = new ThriftClassLoader();
$loader-&registerNamespace("Thrift", __DIR__ . "/thrift/lib");
$loader-&registerDefinition("tService", $GEN_DIR);
$loader-&register();
use Thrift\Transport\TS
use Thrift\Transport\TBufferedT
use Thrift\Protocol\TBinaryP
$socket = new TSocket('localhost', 9090);
$transport = new TBufferedTransport($socket);
$protocol = new TBinaryProtocol($transport);
$client = new \tService\UserServiceClient($protocol);
$transport-&open();
$userName = $client-&getUserNameById(24);
echo $userN
$transport-&close();
} catch (Exception $e) {
echo $e-&getMessage();
server端的代码,在thrift的tutorial中有一个例子,但是生成的php接口类文件中没有“UserServiceProcessor”类,因为默认执行`thrift --gen php UserService.thrift`生成的php文件中是不包含server端的实现的,要使用php写server程序,需添加参数":server",执行`thrift --gen php:server UserService.thrift`命令生产的php接口类中才会有server的实现。不过看server的代码,并是用到socket的类,所以php的server是有些特殊的,它需要apache的支持。
php server代码:ServerDemo.php
error_reporting(E_ALL);
require_once __DIR__ . '/thrift/lib/Thrift/ClassLoader/ThriftClassLoader.php';
use Thrift\ClassLoader\ThriftClassL
$GEN_DIR = realpath(dirname(__FILE__)) . '/gen-php';
$loader = new ThriftClassLoader();
$loader-&registerNamespace('Thrift', __DIR__ . '/thrift/lib');
$loader-&registerDefinition("tService", $GEN_DIR);
$loader-&register();
use Thrift\Protocol\TBinaryP
use Thrift\Transport\TPhpS
use Thrift\Transport\TBufferedT
class UserServiceHandler implements \tService\UserServiceIf
public function getUserNameById($userId)
return "hello, user(id:" . $userId . ")";;
header('Content-Type', 'application/x-thrift');
if (php_sapi_name() == 'cli') {
echo "\r\n";
$userService = new UserServiceHandler();
$processor = new \tService\UserServiceProcessor($userService);
$transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W));
$protocol = new TBinaryProtocol($transport, true, true);
$transport-&open();
$processor-&process($protocol, $protocol);
$transport-&close();
把程序包放到apache配置的web目录,我本机环境为ubuntu12.04,所以把项目拷贝到"/var/www/“目录,ServerDemo.php在项目包ThriftDemo根目录下,所以client端的代码要修改为:
error_reporting(E_ALL);
require_once __DIR__ . "/thrift/lib/Thrift/ClassLoader/ThriftClassLoader.php";
use Thrift\ClassLoader\ThriftClassL
$GEN_DIR = realpath(dirname(__FILE__) . "/gen-php");
$loader = new ThriftClassLoader();
$loader-&registerNamespace("Thrift", __DIR__ . "/thrift/lib");
$loader-&registerDefinition("tService", $GEN_DIR);
$loader-&register();
use Thrift\Transport\TS
use Thrift\Transport\TBufferedT
use Thrift\Protocol\TBinaryP
use Thrift\Transport\THttpC
$socket = new THttpClient('localhost', 80, '/ThriftDemo/ServerDemo.php');
$transport = new TBufferedTransport($socket);
$protocol = new TBinaryProtocol($transport);
$client = new \tService\UserServiceClient($protocol);
$transport-&open();
$userName = $client-&getUserNameById(24);
echo $userN
$transport-&close();
} catch (Exception $e) {
echo $e-&getMessage();
这个时候,运行client的脚本,就可以访问php的thrift server实现类了。第一个的client可以访问java的server,所以php的server不是通过`php ServerDemo.php`来运行脚本的,client端是通过访问apache下的server脚本文件调用服务的。(php的server比java和ruby、python、perl等要繁琐一些,估计也很少用php写thrift的服务端代码)
好的,下个语言!
server代码:server_demo.rb
require '../lib/thrift'
require '../thrift-demo/gen-rb/user_service'
class UserServiceHandler
def getUserNameById(userId)
return "hello, user(id: #{userId})"
handler = UserServiceHandler.new()
processor = UserService::Processor.new(handler)
transport = Thrift::ServerSocket.new('localhost', 9090)
transportFactory = Thrift::BufferedTransportFactory.new()
server = Thrift::SimpleServer.new(processor, transport, transportFactory)
puts "Starting the server..."
server.serve()
client代码:client_demo.rb
require '../lib/thrift'
require '../thrift-demo/gen-rb/user_service'
transport = Thrift::BufferedTransport.new(Thrift::Socket.new("localhost", 9090))
protocol = Thrift::BinaryProtocol.new(transport)
client = UserService::Client.new(protocol)
transport.open()
puts client.getUserNameById(24)
transport.close()
rescue Thrift::Exception =& tx
puts 'Thrift.Exception: ', tx.message
ruby还是很简洁的,执行`thrift --gen rb UserService.thrift`生成ruby的接口类文件,然后依次运行server脚本和client脚本。
四、Python
server代码:ServerDemo.py
__author__ = 'petric'
import sys
sys.path.append('./gen-py')
from UserService import UserService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
class UserServiceHandler:
def getUserNameById(self, id):
return "hello, user(id:%d)" %id
handler = UserServiceHandler()
processor = UserService.Processor(handler)
transport = TSocket.TServerSocket(port=9090)
tFactory = TTransport.TBufferedTransportFactory()
pFactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tFactory, pFactory)
print "starting py server..."
server.serve()
client代码:ClientDemo.py
__author__ = 'petric'
import sys
sys.path.append('./gen-py')
from UserService import UserService
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
transport = TSocket.TSocket('localhost', 9090)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = UserService.Client(protocol)
transport.open()
print client.getUserNameById(2)
transport.close()
except Thrift.TException, tx:
print '%s' % (tx.message)
执行`thrift --gen py UserService.thrift`生成ruby的接口类文件,然后依次运行server脚本和client脚本。
但是,这里面还有一个问题,先说java,在pom.xml中加入thrift的依赖配置就可以,这就不说了;php中,在下载的thrift-0.9.1.tar.gz包下的lib目录下有各个语言的thrift的工具包,php下有lib工具包,ruby下也有lib工具包,拿到自己的项目中就行;不过,python和php和ruby不同,它的lib目录下面没有,不过多了个“setup.py“文件,哦,对用python做开发的同学就不用说了,不过对想玩一玩python例子的其它程序员-google一下也就清楚了,执行`sudo python setup.py install`就可以给python添加thrift支持包了。
好,再写一个例子,就当自己也了解一下其它语言的特点了
对perl不是很了解,工作中也还没有用到过,先写client试一试
client代码:ClientDemo.pl
#!/usr/bin/env perl
use lib '../lib';
use lib '../gen-perl';
use Thrift::BinaryP
use Thrift::S
use Thrift::BufferedT
my $socket = new Thrift::Socket('localhost', 9090);
my $transport = new Thrift::BufferedTransport($socket, );
my $protocol = new Thrift::BinaryProtocol($transport);
my $client = new UserServiceClient($protocol);
$transport-&open();
print 'connection open...';
my $name = $client-&getUserNameById(3);
print "$name\n";
$transport-&close();
}; if($@){
warn(Dumper($@));
访问java,python,ruby的server端没有问题,
server代码:ServerDemo.pl
#!/usr/bin/env perl
use lib '../lib';
use lib '../gen-perl';
use Thrift::S
use Thrift::S
package UserServiceH
use base qw(UserServiceIf);
my $classname =
return bless($self,$classname);
sub getUserNameById
my($self, $userId) = @_;
return ("hello, user(id:$userId)\n");
my $handler = new UserServiceH
my $processor = new UserServiceProcessor($handler);
my $serversocket = new Thrift::ServerSocket(9090);
my $forkingserver = new Thrift::ForkingServer($processor, $serversocket);
print "Starting perl server...\n";
$forkingserver-&serve();
}; if($@) {
if ($@ =~ m/TException/ and exists $@-&{message}) {
my $message = $@-&{message};
= $@-&{code};
= $code . ':' . $
我的系统自带的perl的版本是5.14.2,不过和python差不多也得安装一下环境,但不是python那样安装python的thrift工具包,perl也是把它的lib目录拷贝到自己的项目就可以。运行脚本报了一些错误,一些类啊文件什么的好像没有,google一下,下载了Class-Accessor-0.34.tar.gz,然后安装上(解压,make install),又执行`sudo apt-get install libbit-vector-perl`,把perl的lib下的文件也跑了一下`perl Makefile.PL`和 `make install`。这样perl脚本的server和client都可以跑了,测试正常输出结果。
在tutorial中还有js的例子,js不能访问通常的server的,都是通过socket创建的,只能通过ajax访问通过JSON protocol 和 HTTP transport开启的服务,照着tutorial的例子写了一遍,server用java写的,用到apache的httpcomponents包,启动一个http的server,指定自己的html(包含js的client端)文件所在的目录为webapp,通过设定的端口访问自己的html页面,如““,这样js就可以访问thrift的接口服务了!哇~,这个例子最麻烦了,代码就不拷贝过来了。由于js的ajax通常情况下是跨不了域的,所以js的client端和server端需在一个域名下,例子中使用的HttpService相当与模拟了一个web server(apache,tomcat等),那js请求的是一个url,如“/UserService/getUserNameById“,server端遇到该url会通过Processor调用实现类返回结果,其它的文件url就直接返回文件了。简单点就可以理解为:js要想访问thrift的service服务需通过web server这样一个中间层。
一条路一个人
浏览: 8445 次
来自: 定州市thrift的使用介绍 -
- ITeye技术网站
一、About& thrift&&
二、什么是thrift,怎么工作?
三、Thrift& IDL
四、Thrift&& Demo
五、Thrift 协议栈 以及各层的使用(java 为例)
六、与protocolbuffer的区别
一、About& thrift&&
&&&&&&&& thrift是一种可伸缩的跨语言服务的发展软件框架。它结合了功能强大的软件堆栈的代码生成引擎,以建设服务,工作效率和无缝地与C + +,C#,Java,Python和PHP和Ruby结合。thrift是facebook开发的,我们现在把它作为开源软件使用。thrift允许你定义一个简单的定义文件中的数据类型和服务接口。以作为输入文件,编译器生成代码用来方便地生成RPC客户端和服务器通信的无缝跨编程语言(来自百度百科)。&&&
& &&&最初由facebook开发用做系统内个语言之间的RPC通信 。
& &&&2007年由facebook贡献到apache基金 ,现在是apache下的opensource之一 。
& &&&支持多种语言之间的RPC方式的通信:php语言client可以构造一个对象,调用相应的服务方法来调用java语言的服务 ,跨越语言的C/S&& rpc& 调用 。
二、什么是thrift,怎么工作?
java& rmi的例子,代码见附件,建立一个java rmi的流程& :
& &&&定义一个服务调用接口 。
& &&&server端:接口实现---impl的实例---注册该服务实现(端口)---启动服务。
& &&&client端:通过ip、端口、服务名,得到服务,通过接口来调用 。
& &&&rmi数据传输方式:java对象序列化 。
Thrift& 服务&
& &&&例同rmi ,需要定义通信接口、实现、注册服务、绑定端口……
& &&&如何多种语言之间通信& ?
& &&&数据传输走socket(多种语言均支持),数据再以特定的格式(String ),发送,接收方语言解析&& 。
&&&&&&& Object ---&& String ---&& Object& 。
&&& 问题:编码、解析完全需要自己做 ,复杂的数据结构会编码困难 .
Thrift& 服务 :thrift的中间编码层
& &&&java& Object ---& Thrift& Object ---& php& Object&&
& &&& 定义thrift的文件 ,由thrift文件(IDL)生成 双方语言的接口、model ,在生成的model以及接口中会有解码编码的代码 。
& &&&thrift&& 文件例子
&&&& thrift-0.7.0.exe&& -r&& -gen& java&&& TestThrift.thrift&&& 生成java 代码
&&&& thrift-0.7.0.exe&& -r&& -gen& php&&& TestThrift.thrift&&& 生成php代码
&&&& thrift-0.7.0.exe&& -r&& -gen& py&&&&&& TestThrift.thrift&&& 生成python代码
&&&& thrift-0.7.0.exe&& -r&& -gen& as3&&&& TestThrift.thrift&&& 生成as3代码
&&&& thrift-0.7.0.exe&& -r&& -gen& cpp&&&& TestThrift.thrift&&& 生成C++代码
三、Thrift& IDL
&&&&&&&&&&&&&&&&
&&&&&& /tianhuilove/archive//2167669.html
&&&&&& http://wiki.apache.org/thrift/
&&&&&&&&&&
&&&&&& http://wiki.apache.org/thrift/ThriftTypes
四、Thrift&& Demo
Thrift& IDL 文件
namespace java com.gemantic.analyse.thrift.index
NewsModel{
4:string media_
service IndexNewsOperatorServices {
bool indexNews(1:NewsModel indexNews),
bool deleteArtificiallyNews(1:i32 id )
java& server
package com.gemantic.analyse.thrift.
import java.net.InetSocketA
import org.apache.thrift.protocol.TBinaryP
import org.apache.thrift.server.TS
import org.apache.thrift.server.TThreadPoolS
import org.apache.thrift.server.TThreadPoolServer.A
import org.apache.thrift.transport.TServerS
import org.apache.thrift.transport.TServerT
import org.apache.thrift.transport.TTransportF
public class ThriftServerTest {
* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
IndexNewsOperatorServices.Processor processor = new IndexNewsOperatorServices.Processor(new IndexNewsOperatorServicesImpl());
TServerTransport serverTransport = new TServerSocket( new InetSocketAddress("0.0.0.0",9813));
Args trArgs=new Args(serverTransport);
trArgs.processor(processor);
//使用二进制来编码应用层的数据
trArgs.protocolFactory(new TBinaryProtocol.Factory(true, true));
//使用普通的socket来传输数据
trArgs.transportFactory(new TTransportFactory());
TServer server = new TThreadPoolServer(trArgs);
System.out.println("server begin ......................");
server.serve();
System.out.println("---------------------------------------");
server.stop();
}catch(Exception e){
throw new RuntimeException("index thrift server start failed!!"+"/n"+e.getMessage());
java client
package com.gemantic.analyse.thrift.
import org.apache.thrift.TE
import org.apache.thrift.protocol.TBinaryP
import org.apache.thrift.protocol.TP
import org.apache.thrift.transport.TS
import org.apache.thrift.transport.TT
public class ThriftClientTest {
* @param args
* @throws TException
public static void main(String[] args) throws TException {
// TODO Auto-generated method stub
TTransport transport = new TSocket("10.0.0.41", 9813);
long start=System.currentTimeMillis();
TTransport transport = new TSocket("218.11.178.110",9090);
TProtocol protocol = new TBinaryProtocol(transport);
IndexNewsOperatorServices.Client client=new IndexNewsOperatorServices.Client(protocol);
transport.open();
client.deleteArtificiallyNews(123456);
NewsModel newsModel=new NewsModel();
newsModel.setId(789456);
newsModel.setTitle("this from java client");
newsModel.setContent(" 世界杯比赛前,由于塞尔维亚和黑山突然宣布分裂,国际足联开会决定剔除塞黑,由世界上球迷最多的国家顶替,名额恰巧来到中国。举国上下一片欢腾,中国足协决定由“成世铎”(成龙+阎世铎)组队,进军世界杯。");
newsModel.setAuthor("ddc");
newsModel.setMedia_from("新华08");
client.indexNews(newsModel);
transport.close();
System.out.println((System.currentTimeMillis()-start));
System.out.println("client sucess!");
php client
$GLOBALS['THRIFT_ROOT'] = '/home/tjiang/demo/thrift/lib/php/src';
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php';
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/THttpClient.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';
include_once $GLOBALS['THRIFT_ROOT'].'/packages/TestThrift/TestThrift_types.php';
include_once $GLOBALS['THRIFT_ROOT'].'/packages/TestThrift/IndexNewsOperatorServices.php';
$data=array(
'id'=&'1',
'title'=&'demo-标题',
'content'=&'demo-内容',
'media_from'=&'hexun',
'author'=&'xiaodi667'
$thrif_server_url = '10.0.0.41';
$transport = new TSocket($thrif_server_url, 9813);
$transport-&open();
$protocol = new TBinaryProtocol($transport);
$client= new IndexNewsOperatorServicesClient($protocol, $protocol);
$obj = new NewsModel($data);
$result = $client-&indexNews($obj);
$transport-&close();
python client
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import sys
from TestThrift.ttypes import NewsModel
from TestThrift.IndexNewsOperatorServices import Client
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
# Make socket
transport = TSocket.TSocket('10.0.0.41', 9813)
# Buffering is critical. Raw sockets are very slow
transport = TTransport.TBufferedTransport(transport)
# Wrap in a protocol
protocol = TBinaryProtocol.TBinaryProtocol(transport)
# Create a client to use the protocol encoder
client = Client(protocol)
# Connect!
transport.open()
client.deleteArtificiallyNews(123)
newsModel=NewsModel()
newsModel.id=123456
newsModel.title="python Test"
newsModel.content="client test
come from python";
newsModel.media_from="xinhua08"
client.indexNews(newsModel)
transport.close()
except Thrift.TException, tx:
print '%s' % (tx.message)
Csharp client
TTransport transport = new TSocket("10.0.0.41", 9813);
TProtocol protocol = new TBinaryProtocol(transport);
IndexNewsOperatorServices.Client client = new IndexNewsOperatorServices.Client(protocol);
transport.Open();
NewsModel model = new NewsModel();
model.Author = "jww";
model.Title = "title";
model.Content = "client
model.Id = 1;
client.deleteArtificiallyNews(123);
Console.WriteLine(client.indexNews(model));
五、Thrift 协议栈 以及各层的使用(java 为例)
1、model&& interface
&&&&&& 服务的调用接口以及接口参数model、返回值model
2、Tprotocol&&& 协议层
&&&&&&&& 将数据(model)编码 、解码 。
3、Ttramsport 传输层
&&&&&&& 编码后的数据传输(简单socket、http)
5、Tserver
&&&&&&& 服务的Tserver类型,实现了几种rpc调用(单线程、多线程、非阻塞IO)
六、与protocolbuffer的区别
/development/346.html
&&&&&&&&&&&
/questions/69316/biggest-differences-of-thrift-vs-protocol-buffers
区别:
1、Another important difference are the languages supported by default.&&& protobuf: Java, C++, Python&&& Thrift: Java, C++, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk, Ocaml
支持语言不同,thrift支持着更多的语言 。
2、Thrift supports ‘exceptions 。
&& thrift支持服务的异常 。
3、Protocol Buffers much easier to read 。Protobuf API looks cleaner, though the generated classes are all packed as an inner classes which is not so nice.
&& Protocol Buffers 在文档方面比thrift丰富,而且比thrift简单 。
4、Protobuf serialized objects are about 30% smaller then Thrift.
&& Protocol Buffers在序列化/反序列化、传输上性能更优 。
5、RPC is another key difference. Thrift generates code to implement RPC clients and servers wheres Protocol Buffers seems mostly designed as a data-interchange format alone.&
&&& thrift提供了一套完整的rpc服务实现(多线程socket、非阻塞的socket....)
6、And according to the wiki the Thrift runtime doesn't run on Windows.
&& thrift 对有些语言在windows上不支持:C++&& .....
下载次数: 1099
浏览 118036
浏览: 266855 次
来自: 北京
既想支持低版本IE浏览器如IE6,又想使用websocket作 ...
在Drools的眼里,世界是由是由各种规则/流程/事件构成的
请问 这边有异步调用的例子吗
代码看起来好乱
不错,对比挺好

我要回帖

更多关于 微信摩拜单车要押金吗 的文章

 

随机推荐