PHP通过thrift调用Python函数

步骤:

(1)创建Thrift的语法规则文件,命名为xuejiehome.thrift

namespace php xuejiehome_thrift
namespace py xuejiehome_thrift
   
service xuejiehome {
    void execute(1:string date, 2:string action)
    string progress(1:string date, 2: string action)
}

  注:定义两个可被调用的函数名称和参数,execute和progress

(2)安装thrift并生成PHP对应的类

wget http://www.apache.org/dyn/closer.cgi?path=/thrift/0.9.2/thrift-0.9.2.tar.gz
tar zxvf thrift-0.9.2.tar.gz
cd thrift-0.9.2
./bootstrap.sh
./configure
make && make install
thrift --gen php xuejiehome_thrift   # 生成文件夹gen-php

(3)将上一步中生成的 gen-php 文件夹 放至 thrift 目录下

(4)将thrift源码下的thrift扩展文件 拷贝至 thrift 目录下

cp thrift-0.9.2/lib/php/lib/Thrift thrift/
ls -al thrift
   
wyl-mac:thrift wyl$ ls -al 
total 0
drwxrwxrwx   4 wyl  staff  136  3 26 10:53 .
drwxrwxrwx  15 wyl  staff  510  4 23 09:27 ..
drwxrwxrwx  12 wyl  staff  408  3 26 10:53 Thrift
drwxrwxrwx   3 wyl  staff  102  3 26 10:53 gen-php

   注:thrift目录为PHP项目中的第三方扩展库目录,可根据需要放置

(5)编写python服务端


#!/usr/bin/env python
#-*- encoding: utf-8 -*-
  
from vendor.core import config
config.init()
from vendor.xuejiehome_thrift import ttypes, constants,xuejiehome
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from src.handler import Handler
import signal
  
import sys, os
  
VERSION = "0.5.1"
  
def signal_handle(n):
    if n == 2:
        print "进程被终止"
        sys.exit(0)
  
def signal_start():
    signal.signal(signal.SIGINT, signal_handle)
  
class server():
  
    def run(self):
        signal_start()
  
        processor = None
  
        h = Handler()
        processor = xuejiehome.Processor(h)
  
        transport = TSocket.TServerSocket(config.thrift.host, config.thrift.port)
        tfactory = TTransport.TBufferedTransportFactory()
        pfactory = TBinaryProtocol.TBinaryProtocolFactory()
        server = TServer.TForkingServer(processor, transport, tfactory, pfactory)
        print "Thrift Server version: [%s]" % VERSION
        print "listen: %s:%s" % (config.thrift.host, config.thrift.port)
        print "\033[33m[Info] start handle server\033[0m"
        server.serve()
  
if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "daemon":
        #创建守护进程
        print "\033[33m[Info] start daemon mode.\033[0m"
        try:
            if os.fork() > 0:
                os._exit(0)
        except OSError, error:
            print '\033[31m[Error]fork #1 failed: %d (%s)\033[0m' % (error.errno, error.strerror)
            os._exit(1)
        os.chdir('/')
        os.setsid()
        os.umask(0)
    serve = server()
    serve.run()

(6)编写php客户端——thriftClient.php

<?php
namespace Xj\CoreBundle\Services;
use Thrift\ClassLoader\ThriftClassLoader;
use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TSocket;
use Thrift\Transport\THttpClient;
use Thrift\Transport\TBufferedTransport;
use Thrift\Exception\TException;
 
class ThriftBase {
     
    public function __construct(CommonConfig $config) {
        $this->path=dirname($_SERVER['DOCUMENT_ROOT']).'/src/Jy/CoreBundle/Services/thrift';
        $this->host = $config->thrift['THRIFT_HOST'];
        $this->port = $config->thrift['THRIFT_PORT'];
        $this->timeout = $config->thrift['THRIFT_TIMEOUT'];
        require('thrift/Thrift/ClassLoader/ThriftClassLoader.php');
    }
 
    public function connect($host, $port, $timeout) {
        $GEN_DIR ="{$this->path}/gen-php";
        $loader = new ThriftClassLoader();
        $loader->registerNamespace('Thrift',$this->path);
        $loader->registerDefinition('Jy\CoreBundle\Services', $GEN_DIR);
        $loader->register();
        $socket = new TSocket($this->host, $this->port);
        $socket->setRecvTimeout($timeout);
        $this->transport = new TBufferedTransport($socket, 1024, 1024);
        $this->protocol = new TBinaryProtocol($this->transport);
    }
 
    public function __destruct() {
        $this->transport->close();
    }
}
 
class ThriftRefreshClient extends ThriftBase{
    function call_progress($date) {
        $this->connect($this->host, $this->port, $this->timeout);
        include "{$this->path}/gen-php/xuejiehome_thrift/xuejiehome.php";
        $client = new \xuejiehome_thrift\xuejiehomeClient($this->protocol);
        $this->transport->open();
        $client->progress($date,'test'); # 调用 progress函数
    }
}



by 雪洁 2015-08-06 06:42:39 1928 views
我来说几句

相关文章