search
Homephp教程php手册(转)使用Thrift0.9.1实现跨语言调用Golang、Php、Python、Java

问题导读: 什么是Thrift? Thrift的官方网站在哪里? Golang、Java、Python、PHP之间如何通过Thrift实现跨语言调用? 一、什么是Thrift Thrift是一种可伸缩的跨语言服务的发展软件框架。它结合了功能强大的软件堆栈的代码生成引擎,以建设服务。 Thrift是fac

问题导读:
什么是Thrift?
Thrift的官方网站在哪里?
Golang、Java、Python、PHP之间如何通过Thrift实现跨语言调用?

(转)使用Thrift0.9.1实现跨语言调用Golang、Php、Python、Java



一、什么是Thrift
  Thrift是一种可伸缩的跨语言服务的发展软件框架。它结合了功能强大的软件堆栈的代码生成引擎,以建设服务。
  Thrift是facebook开发的,07年4月开放源代码,08年5月进入apache孵化器。创造Thrift是为了解决facebook系统中各系统间大数据量的传 输通信以及系统之间语言环境不同需要跨平台的特性。所以thrift可以支持多种程序语言,例如:  C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml. (目前0.9.1版本已经开始支持golang语言)在多种不同的语言之间通信thrift可以作为二进制的高性能的通讯中间件,支持数据(对象)序列化和多种类型的RPC服务。
  Thrift允许你定义一个简单的定义文件中的数据类型和服务接口。以作为输入文件,编译器生成代码用来方便地生成RPC客户端和服务器通信的无缝跨编程语言。简而言之,开发者只需准备一份thrift脚本,通过thrift code generator(像gcc那样输入一个命令)就能生成所要求的开发语言代码。

  类似Thrift的工具,还有Avro、protocol buffer,但相对于Thrift来讲,都没有Thrift支持全面和使用广泛。

1) thrift内部框架一瞥
  按照官方文档给出的整体框架,Thrift自下到上可以分为4层:
+-------------------------------------------+
| Server                                         |  -- 服务器进程调度
| (single-threaded, event-driven etc) |
+-------------------------------------------+
| Processor                                      |  -- RPC接口处理函数分发,IDL定义接口的实现将挂接到这里面
| (compiler generated)                      |
+-------------------------------------------+
| Protocol                                         |  -- 协议
| (JSON, compact etc)                       |
+-------------------------------------------+
| Transport                                      |  -- 网络传输
| (raw TCP, HTTP etc)                       |
+-------------------------------------------+

  Thrift实际上是实现了C/S模式,通过代码生成工具将接口定义文件生成服务器端和客户端代码(可以为不同语言),从而实现服务端和客户端跨语言的支持。用户在Thirft描述文件中声明自己的服务,这些服务经过编译后会生成相应语言的代码文件,然后用户实现服务(客户端调用服务,服务器端提服务)便可以了。其中protocol(协议层, 定义数据传输格式,可以为二进制或者XML等)和transport(传输层,定义数据传输方式,可以为TCP/IP传输,内存共享或者文件共享等)被用作运行时库。

2)支持的数据传输格式、数据传输方式和服务模型
    (a)支持的传输格式
      TBinaryProtocol – 二进制格式.
      TCompactProtocol – 压缩格式
      TJSONProtocol – JSON格式
      TSimpleJSONProtocol –提供JSON只写协议, 生成的文件很容易通过脚本语言解析。
      TDebugProtocol – 使用易懂的可读的文本格式,以便于debug
    (b) 支持的数据传输方式
      TSocket -阻塞式socker
      TFramedTransport – 以frame为单位进行传输,非阻塞式服务中使用。
      TFileTransport – 以文件形式进行传输。
      TMemoryTransport – 将内存用于I/O. java实现时内部实际使用了简单的ByteArrayOutputStream。
      TZlibTransport – 使用zlib进行压缩, 与其他传输方式联合使用。当前无java实现。
    (c)支持的服务模型
      TSimpleServer – 简单的单线程服务模型,常用于测试
      TThreadPoolServer – 多线程服务模型,使用标准的阻塞式IO。
      TNonblockingServer – 多线程服务模型,使用非阻塞式IO(需使用TFramedTransport数据传输方式)

    3) Thrift IDL
  Thrift定义一套IDL(Interface Definition Language)用于描述接口,通常后缀名为.thrift,通过thrift程序把.thrift文件导出成各种不一样的代码的协议定义。IDL支持的类型可以参考这里:http://thrift.apache.org/docs/types

二、Thrift的官方网站在哪里?
  http://thrift.apache.org/


三、在哪里下载?需要哪些组件的支持?
  Thrift的官方下载地址在这里:http://www.apache.org/dyn/closer ... thrift-0.9.1.tar.gz
  (现在官网打包后的0.9.1版本在make的时候会出各种问题,后文会介绍不建议使用官网提供的0.9.1包)

  Thrift的安装依赖,以及相关语言支持所需要的库,以下是来自官方文档的介绍:
    Basic requirements
      A relatively POSIX-compliant *NIX system
        Cygwin or MinGW can be used on Windows
      g++ 4.2
      boost 1.53.0
      Runtime libraries for lex and yacc might be needed for the compiler.
    Requirements for building from source
      GNU build tools:
        autoconf 2.65
        automake 1.9
        libtool 1.5.24
      pkg-config autoconf macros (pkg.m4)
      lex and yacc (developed primarily with flex and bison)
      libssl-dev
    Language requirements
    These are only required if you choose to build the libraries for the given language
      C++
        Boost 1.53.0
        libevent (optional, to build the nonblocking server)
        zlib (optional)
      Java
        Java 1.7
        Apache Ant
      C#: Mono 1.2.4 (and pkg-config to detect it) or Visual Studio 2005+
      Python 2.6 (including header files for extension modules)
      PHP 5.0 (optionally including header files for extension modules)
      Ruby 1.8
        bundler gem
      Erlang R12 (R11 works but not recommended)
      Perl 5
        Bit::Vector
        Class::Accessor

四、如何安装?
1) 安装依赖插件

  1. root@m1:/home/hadoop#sudo apt-get install libboost-dev libboost-test-dev libboost-program-options-dev libevent-dev automake libtool flex bison pkg-config g++ libssl-dev
复制代码


2) 安装最新版PHP5(因为后文会使用PHP来测试客户端与Golang服务端的交互)

  1. #先添加phpkey
  2. root@m2:/home/hadoop/thrift-git# add-apt-repository ppa:ondrej/php5
  3. You are about to add the following PPA to your system:
  4. This branch follows latest PHP packages as maintained by me & rest of the Debian pkg-php team.
  5. You can get more information about the packages at https://sury.org
  6. If you need to stay with PHP 5.4 you can use the oldstable PHP repository:
  7.     ppa:ondrej/php5-oldstable
  8. BUGS&FEATURES: This PPA now has a issue tracker: https://deb.sury.org/pages/bugreporting.html
  9. PLEASE READ: If you like my work and want to give me a little motivation, please consider donating: https://deb.sury.org/pages/donate.html
  10. More info: https://launchpad.net/~ondrej/+archive/ubuntu/php5
  11. Press [ENTER] to continue or ctrl-c to cancel adding it
  12. gpg: 钥匙环‘/tmp/tmpZ7PZIy/secring.gpg’已建立
  13. gpg: 钥匙环‘/tmp/tmpZ7PZIy/pubring.gpg’已建立
  14. gpg: 下载密钥‘E5267A6C’,从 hkp 服务器 keyserver.ubuntu.com
  15. gpg: /tmp/tmpZ7PZIy/trustdb.gpg:建立了信任度数据库
  16. gpg: 密钥 E5267A6C:公钥“Launchpad PPA for Ond?ej Sury”已导入
  17. gpg: 合计被处理的数量:1
  18. gpg:               已导入:1  (RSA: 1)
  19. OK
  20. root@m2:/home/hadoop/thrift-git# apt-get update
  21. root@m1:/home/hadoop/thrift-git# apt-get install php5-dev php5-cli phpunit
复制代码


3) 下载thirft0.9.1版本

  1. root@m2:/home/hadoop# git clone https://github.com/apache/thrift.git thrift-git
  2. Cloning into 'thrift-git'...
  3. remote: Counting objects: 37193, done.
  4. remote: Compressing objects: 100% (216/216), done.
  5. remote: Total 37193 (delta 319), reused 407 (delta 272)
  6. Receiving objects: 100% (37193/37193), 9.62 MiB | 50 KiB/s, done.
  7. Resolving deltas: 100% (25794/25794), done.
  8. root@m1:/home/hadoop#cd thrift-git
  9. root@m2:/home/hadoop/thrift-git# git checkout -b 0.9.1
  10. Switched to a new branch '0.9.1'
复制代码


4) 编译安装

  1. root@m1:/home/hadoop/thrift-git#./bootstrap.sh
  2. root@m1:/home/hadoop/thrift-git# ./configure --enable-thrift_protocol
  3. #下面是截取部分运行成功后的信息
  4. thrift 0.9.1
  5. Building C++ Library ......... : yes
  6. Building C (GLib) Library .... : yes
  7. Building Java Library ........ : no
  8. Building C# Library .......... : no
  9. Building Python Library ...... : yes
  10. Building Ruby Library ........ : no
  11. Building Haskell Library ..... : no
  12. Building Perl Library ........ : no
  13. Building PHP Library ......... : yes
  14. Building Erlang Library ...... : no
  15. Building Go Library .......... : no
  16. Building D Library ........... : no
  17. C++ Library:
  18.    Build TZlibTransport ...... : yes
  19.    Build TNonblockingServer .. : yes
  20.    Build TQTcpServer (Qt) .... : no
  21. Python Library:
  22.    Using Python .............. : /usr/bin/python
  23. PHP Library:
  24.    Using php-config .......... : /usr/bin/php-config
  25. If something is missing that you think should be present,
  26. please skim the output of configure to find the missing
  27. component.  Details are present in config.log.
复制代码


如果在安装Thrift时,不需要支持的扩展,可以在使用./configure的时候带上以下参数

  1. ./configure --without-php --without-ruby --without-haskell --without-python --without-perl
复制代码


继续安装这个时间会长一点

  1. root@m2:/home/hadoop/thrift-git# make
  2. root@m2:/home/hadoop/thrift-git# make install
复制代码


我们可以看到thrift已经安装完成,当前版本是0.9.1

  1. root@m1:/home/hadoop/thrift-git# thrift -version
  2. Thrift version 0.9.1
复制代码



五、Golang、Java、Python、PHP之间通过Thrift实现跨语言调用
  在写代码之前,我们先来配置Thrift的协议库IDL文件:

  1. root@m1:/home/hadoop/thrift-git/tutorial# vi idoall.org.thrift 
  2. namespace go idoall.org.demo
  3. namespace java idoall.org.demo
  4. namespace php idoall.org.demo
  5. namespace  py idoall.org.demo
  6. struct Student{
  7. 1: i32 sid, 
  8. 2: string sname,
  9. 3: bool ssex=0,
  10. 4: i16 sage,
  11. }
  12. const map MAPCONSTANT = {'hello':'world', 'goodnight':'moon'}
  13. service idoallThrift {        
  14.         list CallBack(1:i64 callTime, 2:string name, 3:map paramMap),
  15.         void put(1: Student s),
  16. }
复制代码


编译IDL文件,生成相关代码

  1. root@m1:/home/hadoop/thrift-git/tutorial# thrift -r --gen go idoall.org.thrift 
  2. root@m1:/home/hadoop/thrift-git/tutorial# thrift -r --gen py idoall.org.thrift   
  3. root@m1:/home/hadoop/thrift-git/tutorial# thrift -r --gen php idoall.org.thrift   
  4. root@m1:/home/hadoop/thrift-git/tutorial# thrift -r --gen java idoall.org.thrift
复制代码


如果编译IDL的PHP包要生成server端代码,和其他语言不太一样,可以使用thrift --help查看使用说明,需要加上server选项,如下:

  1. root@m1:/home/hadoop/thrift-git/tutorial# thrift -r --gen php:server idoall.org.thrift
复制代码


1) Golang 客户端和服务端的实现及交互
        Golang1.3的安装,请参考这篇文章《ubuntu12.04 64bit基于源码安装golang1.3》,默认使用apt-get安装不是最新版。

        #安装golang的Thrift包:


  1. root@m1:/home/hadoop/thrift-git/tutorial# go get git.apache.org/thrift.git/lib/go/thrift
复制代码


#将Thrift生成的开发库也复制到GOPATH中

  1. root@m1:/home/hadoop/thrift-git/tutorial# cp -r /home/hadoop/thrift-git/tutorial/gen-go/idoall $GOPATH/src
复制代码


#编写go server端代码(后面的代码,我们都放在/home/hadoop/thrift_demo目录中进行演示)

  1. root@m1:/home/hadoop# mkdir thrift_demo
  2. root@m1:/home/hadoop# cd thrift_demo/
  3. root@m1:/home/hadoop/thrift_demo# vi s.go
复制代码

  1. package main
  2. import (
  3.     "idoall/org/demo"
  4.     "fmt"
  5.     "git.apache.org/thrift.git/lib/go/thrift"
  6.     "os"
  7. )
  8. const (
  9.     NetworkAddr = "0.0.0.0:10086"
  10. )
  11. type idoallThrift struct {
  12. }
  13. func (this *idoallThrift) CallBack(callTime int64, name string, paramMap map[string]string) (r []string, err error) {
  14.     fmt.Println("-->from client Call:", callTime, name, paramMap)
  15.     r = append(r, "key:"+paramMap["a"]+"    value:"+paramMap["b"])
  16.     return
  17. }
  18. func (this *idoallThrift) Put(s *demo.Student) (err error){
  19.     fmt.Printf("Stduent--->id: %d\tname:%s\tsex:%t\tage:%d\n", s.Sid, s.Sname, s.Ssex, s.Sage)
  20.     return nil
  21. }
  22. func main() {
  23.     transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
  24.     protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
  25.     //protocolFactory := thrift.NewTCompactProtocolFactory()
  26.     serverTransport, err := thrift.NewTServerSocket(NetworkAddr)
  27.     if err != nil {
  28.         fmt.Println("Error!", err)
  29.         os.Exit(1)
  30.     }
  31.     handler := &idoallThrift{}
  32.     processor := demo.NewIdoallThriftProcessor(handler)
  33.     server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory)
  34.     fmt.Println("thrift server in", NetworkAddr)
  35.     server.Serve()
  36. }
复制代码


#编写go client端代码

  1. root@m1:/home/hadoop/thrift_demo# vi c.go
  2. package main
  3. import (
  4.     "idoall/org/demo"
  5.     "fmt"
  6.     "git.apache.org/thrift.git/lib/go/thrift"
  7.     "net"
  8.     "os"
  9.     "time"
  10.     "strconv"
  11. )
  12. const (
  13.     HOST = "127.0.0.1"
  14.     PORT = "10086"
  15. )
  16. func main() {
  17.     startTime := currentTimeMillis()
  18.     transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
  19.     protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
  20.     transport, err := thrift.NewTSocket(net.JoinHostPort(HOST, PORT))
  21.     if err != nil {
  22.         fmt.Fprintln(os.Stderr, "error resolving address:", err)
  23.         os.Exit(1)
  24.     }
  25.     useTransport := transportFactory.GetTransport(transport)
  26.     client := demo.NewIdoallThriftClientFactory(useTransport, protocolFactory)
  27.     if err := transport.Open(); err != nil {
  28.         fmt.Fprintln(os.Stderr, "Error opening socket to "+HOST+":"+PORT, " ", err)
  29.         os.Exit(1)
  30.     }
  31.     defer transport.Close()
  32.     for i := 0; i
  33.         paramMap := make(map[string]string)
  34.         paramMap["a"] = "idoall"
  35.         paramMap["b"] = "org"+strconv.Itoa(i+1)
  36.         r1, _ := client.CallBack(time.Now().UnixNano() / 1000000, "go client", paramMap)
  37.         fmt.Println("GOClient Call->", r1)
  38.     }
  39.     model := demo.Student{11,"student-idoall-go",true,20}
  40.     client.Put(&model)
  41.     endTime := currentTimeMillis()
  42.     fmt.Printf( "本次调用用时:%d-%d=%d毫秒\n",endTime,startTime, (endTime - startTime))
  43. }
  44. func currentTimeMillis() int64 {
  45.     return time.Now().UnixNano() / 1000000
  46. }
复制代码


#运行go服务端(可以看到服务端已经在监听本机的10086端口)

  1. root@m1:/home/hadoop/thrift_demo# go run s.go
  2. thrift server in 0.0.0.0:10086
复制代码


#运行go客户端

  1. root@m1:/home/hadoop/thrift_demo# go run c.go
  2. GOClient Call-> [key:idoall    value:org1]
  3. GOClient Call-> [key:idoall    value:org2]
  4. GOClient Call-> [key:idoall    value:org3]
  5. GOClient Call-> [key:idoall    value:org4]
  6. GOClient Call-> [key:idoall    value:org5]
  7. 本次调用用时:1408267333489-1408267333486=3毫秒
  8. root@m1:/home/hadoop/thrift_demo#
复制代码


#查看go服务端,可以看到数据的交互

  1. root@m1:/home/hadoop/thrift_demo# go run s.go
  2. thrift server in 0.0.0.0:10086
  3. -->from client Call: 1408267333487 go client map[a:idoall b:org1]
  4. -->from client Call: 1408267333487 go client map[a:idoall b:org2]
  5. -->from client Call: 1408267333488 go client map[b:org3 a:idoall]
  6. -->from client Call: 1408267333488 go client map[a:idoall b:org4]
  7. -->from client Call: 1408267333488 go client map[a:idoall b:org5]
  8. Stduent--->id: 11       name:student-idoall-go  sex:true        age:20
复制代码


2) python 客户端的实现与golang 服务端的交互
        #将python用到的Thrift包复制到thrift_demo里面

  1. root@m1:/home/hadoop/thrift_demo# cp -r /home/hadoop/thrift-git/lib/py/build /home/hadoop/thrift_demo/libpy
  2. root@m1:/home/hadoop/thrift_demo# cp -r /home/hadoop/thrift-git/tutorial/gen-py /home/hadoop/thrift_demo/gen-py
复制代码


#编写python client代码

  1. root@m1:/home/hadoop/thrift_demo# vi c.py
  2. #!/usr/bin/env python
  3. # -*- coding: utf-8 -*-
  4. import sys, glob, time,datetime
  5. sys.path.append('gen-py')
  6. sys.path.insert(0, glob.glob('libpy/lib.*')[0])
  7. from idoall.org.demo import idoallThrift
  8. from idoall.org.demo.ttypes import *
  9. from thrift import Thrift
  10. from thrift.transport import TSocket
  11. from thrift.transport import TTransport
  12. from thrift.protocol import TBinaryProtocol
  13. try:
  14.   startTime = time.time()*1000
  15.   # Make socket
  16.   transport = TSocket.TSocket('127.0.0.1', 10086)
  17.   # Framed is critical. Raw sockets are very slow
  18.   transport = TTransport.TFramedTransport(transport)
  19.   # Wrap in a protocol
  20.   protocol = TBinaryProtocol.TBinaryProtocol(transport)
  21.   # Create a client to use the protocol encoder
  22.   client = idoallThrift.Client(protocol)
  23.   # Connect!
  24.   transport.open()
  25.   for i in range(1,6):
  26.     r = client.CallBack(time.time()*1000,"python client",{"a":"idoall","b":"org"+str(i)})
  27.     print "PythonClient Call->%s" %(r)
  28.   u1 = Student()  
  29.   u1.sid=111 
  30.   u1.sname='student-idoall-python' 
  31.   u1.ssex=False
  32.   u1.sage=200
  33.   client.put(u1)
  34.   endTime = time.time()*1000
  35.   print "本次调用用时:%d-%d=%d毫秒" %(endTime,startTime, (endTime - startTime))
  36.   # Close!
  37.   transport.close()
  38. except Thrift.TException, tx:
  39.   print 'ERROR:%s' % (tx.message)
复制代码


#运行go服务端

  1. root@m1:/home/hadoop/thrift_demo# go run s.go
  2. thrift server in 0.0.0.0:10086
复制代码


#运行python客户端

  1. root@m1:/home/hadoop/thrift_demo# python c.py 
  2. PythonClient Call->['key:idoall    value:org1']
  3. PythonClient Call->['key:idoall    value:org2']
  4. PythonClient Call->['key:idoall    value:org3']
  5. PythonClient Call->['key:idoall    value:org4']
  6. PythonClient Call->['key:idoall    value:org5']
  7. 本次调用用时:1408268651648-1408268651646=2毫秒
  8. root@m1:/home/hadoop/thrift_demo#
复制代码


#查看go服务端,可以看到数据的交互

  1. root@m1:/home/hadoop/thrift_demo# go run s.go
  2. thrift server in 0.0.0.0:10086
  3. -->from client Call: 1408268651646 python client map[b:org1 a:idoall]
  4. -->from client Call: 1408268651646 python client map[a:idoall b:org2]
  5. -->from client Call: 1408268651647 python client map[a:idoall b:org3]
  6. -->from client Call: 1408268651647 python client map[a:idoall b:org4]
  7. -->from client Call: 1408268651647 python client map[a:idoall b:org5]
  8. Stduent--->id: 111      name:student-idoall-python      sex:false       age:200
复制代码


3) php 客户端的实现与golang 服务端的交互
        #编译php的Thrift扩展

  1. root@m1:/home/hadoop/thrift_demo# cd /home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol   
  2. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# ls
  3. acinclude.m4    build         config.h.in  config.nice    configure     include     ltmain.sh           Makefile.global   mkinstalldirs            php_thrift_protocol.h   thrift_protocol.la
  4. aclocal.m4      config.guess  config.log   config.status  configure.in  install-sh  Makefile            Makefile.objects  modules                  php_thrift_protocol.lo
  5. autom4te.cache  config.h      config.m4    config.sub     config.w32    libtool     Makefile.fragments  missing           php_thrift_protocol.cpp  run-tests.php
  6. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# phpize
  7. Configuring for:
  8. PHP Api Version:         20121113
  9. Zend Module Api No:      20121212
  10. Zend Extension Api No:   220121212
  11. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# ./configure
  12. ##以下只给出部分输出信息
  13. checking for grep that handles long lines and -e... /bin/grep
  14. checking for egrep... /bin/grep -E
  15. checking for a sed that does not truncate output... /bin/sed
  16. checking for cc… cc
  17. config.status: creating config.h
  18. config.status: config.h is unchanged
  19. config.status: executing libtool commands
  20. #执行make命令后,我们可以看到扩展文件放到了/usr/lib/php5/20121212/目录
  21. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# make && make install
  22. Build complete.
  23. Don't forget to run 'make test'.
  24. Installing shared extensions:     /usr/lib/php5/20121212/
复制代码


#让PHP支持thrift,编辑php.ini文件,搜索extension_dir,然后在下面加上extension=thrift_protocol.so,保存退出。

  1. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# vi /etc/php5/fpm/php.ini
  2. ; Directory in which the loadable extensions (modules) reside.
  3. ; http://php.net/extension-dir
  4. ; extension_dir = "./"
  5. ; On windows:
  6. ; extension_dir = "ext"
  7. extension=thrift_protocol.so
复制代码


#重启php5-fpm

  1. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# service php5-fpm restart
  2. php5-fpm stop/waiting
  3. php5-fpm start/running, process 16522
  4. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol#
复制代码


#将php用到的Thrift包复制到thrift_demo里面

  1. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# mkdir -p /home/hadoop/thrift_demo/libphp/
  2. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# cp -r /home/hadoop/thrift-git/lib/php/src/* /home/hadoop/thrift_demo/libphp/
  3. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# cp -r /home/hadoop/thrift-git/lib/php/lib/Thrift /home/hadoop/thrift_demo/libphp
  4. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# cp -r /home/hadoop/thrift-git/tutorial/gen-php /home/hadoop/thrift_demo/gen-php
  5. root@m1:/home/hadoop/thrift-git/lib/php/src/ext/thrift_protocol# cd /home/hadoop/thrift_demo
复制代码


#编写php client端代码

  1. root@m1:/home/hadoop/thrift_demo# vi c.php
  2. $startTime = getMillisecond();
  3. $GLOBALS['THRIFT_ROOT'] = './libphp';   # 指定库目录,可以是绝对路径或是相对路径 
  4. require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/ClassLoader/ThriftClassLoader.php';
  5. use Thrift\ClassLoader\ThriftClassLoader; 
  6. use Thrift\Protocol\TBinaryProtocol; 
  7. use Thrift\Transport\TSocket; 
  8. use Thrift\Transport\TSocketPool; 
  9. use Thrift\Transport\TFramedTransport; 
  10. use Thrift\Transport\TBufferedTransport;
  11. $GEN_DIR = realpath(dirname(__FILE__)).'/gen-php';
  12. $loader = new ThriftClassLoader(); 
  13. $loader->registerNamespace('Thrift', $GLOBALS['THRIFT_ROOT']); # 加载thrift 
  14. $loader->registerDefinition('idoall\org\demo', $GEN_DIR); # 加载自己写的thrift文件编译的类文件和数据定义 
  15. $loader->register();
  16. $socket = new TSocket('127.0.0.1', 10086);     # 建立socket 
  17. $socket->setDebug(TRUE); 
  18. $framedSocket = new TFramedTransport($socket); #这个要和服务器使用的一致 
  19. $transport = $framedSocket; 
  20. $protocol = new TBinaryProtocol($transport);   # 这里也要和服务器使用的协议一致 
  21. $transport->open();
  22. $client= new \idoall\org\demo\idoallThriftClient($protocol);  # 构造客户端
  23. for($i=1;$i
  24. {
  25.     $item = array();
  26.     $item["a"] = "idoall";
  27.     $item["b"] = "org"+$i;
  28.     $result = $client->CallBack(getMillisecond(),"php client",$item); # 对服务器发起rpc调用 
  29.     echo "PHPClient Call->".implode('',$result)."\n";
  30. }
  31. $s = new \idoall\org\demo\Student();
  32. $s->sid=1111;
  33. $s->sname="student-idoall-php";
  34. $s->ssex = false;
  35. $s->sage = 2000;
  36. $client->put($s);
  37. $endTime = getMillisecond();
  38. echo "本次调用用时:".$endTime."-".$startTime."=".($endTime-$startTime)."毫秒\n";
  39. function getMillisecond() {
  40. list($t1, $t2) = explode(' ', microtime());     
  41. return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);  
  42. }
  43. $transport->close();                       # 关闭链接
复制代码


#运行go服务端

  1. root@m1:/home/hadoop/thrift_demo# go run s.go
  2. thrift server in 0.0.0.0:10086
复制代码


#运行php客户端

  1. root@m1:/home/hadoop/thrift_demo# php c.php   
  2. PHPClient Call->key:idoall    value:1
  3. PHPClient Call->key:idoall    value:2
  4. PHPClient Call->key:idoall    value:3
  5. PHPClient Call->key:idoall    value:4
  6. PHPClient Call->key:idoall    value:5
  7. 本次调用用时:1408268739277-1408268739269=8毫秒
复制代码

#查看go服务端,可以看到数据的交互

  1. root@m1:/home/hadoop/thrift_demo# go run s.go
  2. thrift server in 0.0.0.0:10086
  3. -->from client Call: 1408268739272 php client map[a:idoall b:1]
  4. -->from client Call: 1408268739273 php client map[a:idoall b:2]
  5. -->from client Call: 1408268739274 php client map[a:idoall b:3]
  6. -->from client Call: 1408268739275 php client map[a:idoall b:4]
  7. -->from client Call: 1408268739275 php client map[a:idoall b:5]
  8. Stduent--->id: 1111     name:student-idoall-php sex:false       age:2000
复制代码


4) java 客户端的实现与golang 服务端的交互
        #安装maven项目管理工具

  1. root@m1:/home/hadoop/thrift_demo# apt-get install maven
复制代码


#将java用到的Thrift包复制到thrift_demo里面

  1. root@m1:/home/hadoop/thrift_demo# cp -r /home/hadoop/thrift-git/tutorial/gen-java .
  2. root@m1:/home/hadoop/thrift_demo# cd gen-java
  3. root@m1:/home/hadoop/thrift_demo/gen-java# mkdir -p src/main/java
  4. root@m1:/home/hadoop/thrift_demo/gen-java# mkdir META-INF
  5. root@m1:/home/hadoop/thrift_demo/gen-java# mkdir lib
  6. root@m1:/home/hadoop/thrift_demo/gen-java# cp -r /home/hadoop/thrift-git/lib/java/build/libthrift-0.9.1.jar ./lib/
复制代码


#编写java client端代码

  1. root@m1:/home/hadoop/thrift_demo/gen-java# vi idoall/org/demo/c.java
  2. package idoall.org.demo;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import org.apache.thrift.TException;
  7. import org.apache.thrift.protocol.TBinaryProtocol;
  8. import org.apache.thrift.protocol.TProtocol;
  9. import org.apache.thrift.transport.TFramedTransport;
  10. import org.apache.thrift.transport.TSocket;
  11. import org.apache.thrift.transport.TTransport;
  12. import org.apache.thrift.transport.TTransportException;
  13. public class c {
  14.      
  15.     public static final String SERVER_IP = "m1";
  16.     public static final int SERVER_PORT = 10086;
  17.     public static final int TIMEOUT = 30000;
  18.     /**
  19.      * @param args
  20.      */
  21.     public static void main(String[] args) {
  22.          
  23.         long startTime=System.currentTimeMillis();   //获取开始时间
  24.         TTransport transport = null;
  25.         try {
  26.             transport = new TFramedTransport(new TSocket(SERVER_IP,
  27.                     SERVER_PORT, TIMEOUT));
  28.             // 协议要和服务端一致
  29.             TProtocol protocol = new TBinaryProtocol(transport);
  30.             idoallThrift.Client client = new idoallThrift.Client(
  31.                     protocol);
  32.             transport.open();
  33.              
  34.             for(int i=1;i
  35.             {
  36.                 Map m = new HashMap();
  37.                 m.put("a", "idoall");
  38.                 m.put("b", "org"+i);
  39.                  
  40.                 List result = client.CallBack(System.currentTimeMillis(),"java client",m);
  41.                 System.out.println("JAVAClient Call->" + result);
  42.             }
  43.              
  44.             Student s = new Student();
  45.             s.sid=1111;
  46.             s.sname="student-idoall-java";
  47.             s.ssex = true;
  48.             s.sage = 20000;
  49.             client.put(s);
  50.             long endTime = System.currentTimeMillis();
  51.             System.out.println("本次调用用时:" + endTime + "-" + startTime + "=" + (endTime - startTime)+"毫秒");
  52.              
  53.         } catch (TTransportException e) {
  54.             e.printStackTrace();
  55.         } catch (TException e) {
  56.             e.printStackTrace();
  57.         } finally {
  58.             if (null != transport) {
  59.                 transport.close();
  60.             }
  61.         }
  62.     }
  63. }
复制代码


#配置jar包的MANIFEST文件

  1. root@m1:/home/hadoop/thrift_demo/gen-java# vi META-INF/MANIFEST.MF
  2. Manifest-Version: 1.0
  3. Main-Class: idoall.org.demo.c
  4. Class-Path: lib/**.jar
复制代码


#制作Maven的描述文件pom.xml

  1. root@m1:/home/hadoop/thrift_demo/gen-java# vi pom.xml
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.     4.0.0
  4.     idoall.org.demo
  5.     idoall.org.demo
  6.     0.0.1-SNAPSHOT
  7.     jar
  8.     idoall.org.demo
  9.     http://maven.apache.org
  10.    
  11.         UTF-8
  12.    
  13.    
  14.         
  15.             junit
  16.             junit
  17.             3.8.1
  18.             test
  19.         
  20.         
  21.             org.apache.thrift
  22.             libthrift
  23.             0.9.1
  24.         
  25.         
  26.             org.slf4j
  27.             slf4j-log4j12
  28.             1.5.8
  29.         
  30.    
  31.    
  32.         
  33.             
  34.                 maven-assembly-plugin
  35.                
  36.                     
  37.                         
  38.                             idoall.org.demo.c
  39.                         
  40.                     
  41.                     
  42.                         jar-with-dependencies
  43.                     
  44.                
  45.             
  46.             
  47.                 org.apache.maven.plugins
  48.                 maven-compiler-plugin
  49.                
  50.                     1.6
  51.                     1.6
  52.                
  53.             
  54.         
  55.    
复制代码


#使用maven工具,将相关依赖打包到当前目录的target目录中,并生成idoall.org.demo-0.0.1-SNAPSHOT-jar-with-dependencies.jar

  1. root@m1:/home/hadoop/thrift_demo/gen-java# mv idoall src/main/java/
  2. root@m1:/home/hadoop/thrift_demo/gen-java# mvn assembly:assembly
  3. #以下只给出部分提示信息
  4. [INFO] ------------------------------------------------------------------------
  5. [INFO] BUILD SUCCESS
  6. [INFO] ------------------------------------------------------------------------
  7. [INFO] Total time: 7.618s
  8. [INFO] Finished at: Sun Aug 17 09:36:48 CST 2014
  9. [INFO] Final Memory: 12M/29M
  10. [INFO] ------------------------------------------------------------------------
复制代码


#运行go服务端

  1. root@m1:/home/hadoop/thrift_demo# go run s.go
  2. thrift server in 0.0.0.0:10086
复制代码


#运行打包后的java客户端

  1. root@m1:/home/hadoop/thrift_demo/gen-java# java -jar target/idoall.org.demo-0.0.1-SNAPSHOT-jar-with-dependencies.jar 
  2. JAVAClient Call->[key:idoall    value:org1]
  3. JAVAClient Call->[key:idoall    value:org2]
  4. JAVAClient Call->[key:idoall    value:org3]
  5. JAVAClient Call->[key:idoall    value:org4]
  6. JAVAClient Call->[key:idoall    value:org5]
  7. 本次调用用时:1408268973582-1408268973477=105毫秒
复制代码


#查看go服务端,可以看到数据的交互

  1. root@m1:/home/hadoop/thrift_demo# go run s.go
  2. thrift server in 0.0.0.0:10086
  3. -->from client Call: 1408268973547 java client map[a:idoall b:org1]
  4. -->from client Call: 1408268973568 java client map[b:org2 a:idoall]
  5. -->from client Call: 1408268973568 java client map[b:org3 a:idoall]
  6. -->from client Call: 1408268973568 java client map[b:org4 a:idoall]
  7. -->from client Call: 1408268973569 java client map[b:org5 a:idoall]
  8. Stduent--->id: 1111     name:student-idoall-java        sex:true        age:20000
复制代码




(转)使用Thrift0.9.1实现跨语言调用Golang、Php、Python、Java thrift_demo.tar.gz (1.18 MB, 下载次数: 1) 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何在Go中使用命名管道?如何在Go中使用命名管道?May 11, 2023 pm 04:22 PM

命名管道是一种在操作系统中相对比较低级的进程通信方式,它是一种以文件为中介的进程通信方式。在Go语言中,通过os包提供了对命名管道的支持。在本文中,我们将介绍如何在Go中使用命名管道来实现进程间通信。一、命名管道的概念命名管道是一种特殊的文件,可以被多个进程同时访问。在Linux系统中,命名管道是一种特殊的文件类型,它们存在于文件系统的某个位置上,并且可以在

如何在Go中使用第三方库?如何在Go中使用第三方库?May 11, 2023 pm 03:30 PM

在Go语言中,使用第三方库是非常方便的。许多优秀的第三方库和框架可以帮助我们快速地开发应用程序,同时也减少了我们自己编写代码的工作量。但是如何正确地使用第三方库,确保其稳定性和可靠性,是我们必须了解的一个问题。本文将从以下几个方面介绍如何使用第三方库,并结合具体例子进行讲解。一、第三方库的获取Go语言中获取第三方库有以下两种方式:1.使用goget命令首先

如何在PHP中使用协程?如何在PHP中使用协程?May 12, 2023 am 08:10 AM

随着传统的多线程模型在高并发场景下的性能瓶颈,协程成为了PHP编程领域的热门话题。协程是一种轻量级的线程,能够在单线程中实现多任务的并发执行。在PHP的语言生态中,协程得到了广泛的应用,比如Swoole、Workerman等框架就提供了对协程的支持。那么,如何在PHP中使用协程呢?本文将介绍一些基本的使用方法以及常见的注意事项,帮助读者了解协程的运作原理,以

如何在PHP中使用变量函数如何在PHP中使用变量函数May 18, 2023 pm 03:52 PM

变量函数是指可以使用变量来调用函数的一种特殊语法。在PHP中,变量函数是非常有用的,因为它可以让我们更加灵活地使用函数。在本文中,我们将介绍如何在PHP中使用变量函数。定义变量函数在PHP中,变量函数的定义方式非常简单,只需要将要调用的函数名赋值给一个变量即可。例如,下面的代码定义了一个变量函数:$func='var_dump';这里将var_dump函

如何在 Windows 11 中按需使用 OneDrive 的文件如何在 Windows 11 中按需使用 OneDrive 的文件Apr 14, 2023 pm 12:34 PM

<p>Windows 系统上的 OneDrive 应用程序允许您将文件存储在高达 5 GB 的云上。OneDrive 应用程序中还有另一个功能,它允许用户选择一个选项,是将文件保留在系统空间上还是在线提供,而不占用您的系统存储空间。此功能称为按需文件。在这篇文章中,我们进一步探索了此功能,并解释了有关如何在 Windows 11 电脑上的 OneDrive 中按需使用文件的各种选项。</p><h2>如何使用 On

如何在Go中使用WebSocket?如何在Go中使用WebSocket?May 11, 2023 pm 04:17 PM

近年来,WebSocket技术已经成为了Web开发中不可或缺的一部分。WebSocket是一种在单个TCP连接上进行全双工通信的协议,它使得客户端和服务器之间的通信更加流畅和高效。如今,很多现代的Web应用程序都使用了WebSocket技术,例如实时聊天、在线游戏以及实时数据可视化等。Go语言作为一个现代的编程语言,自然也提供了很好的支持WebSock

如何在Go中使用音频处理?如何在Go中使用音频处理?May 11, 2023 pm 04:37 PM

随着音频处理在各种应用场景中的普及,越来越多的程序员开始使用Go编写音频处理程序。Go语言作为一种现代化的编程语言,具有优秀的并发性和高效率的特点,使用它进行音频处理十分方便。本文将介绍如何在Go中使用音频处理技术,包括读取、写入、处理和分析音频数据等方面的内容。一、读取音频数据在Go中读取音频数据有多种方式。其中比较常用的是使用第三方库进行读取,比如go-

如何在PHP中使用数据聚合函数如何在PHP中使用数据聚合函数May 18, 2023 pm 02:51 PM

数据聚合函数是一种用于处理数据库表中多行数据的函数。在PHP中使用数据聚合函数可以使得我们方便地进行数据分析和处理,例如求和、平均数、最大值、最小值等。下面将介绍如何在PHP中使用数据聚合函数。一、介绍常用的数据聚合函数COUNT():计算某一列的行数。SUM():计算某一列的总和。AVG():计算某一列的平均值。MAX():取出某一列的最大值。MIN():

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.