定义IDL文件hello.thrift
struct User {
1: string firstname
2: string lastname
}
exception UserException {
1: i32 error_code,
2: string error_msg
}
service UserManager {
void ping(),
string get_user(1:string firstname,2:string lastname) throws(1:UserException e),
oneway void clear_list()
}
生成python和php文件
thrift -r --gen php hello.thrift
thrift -r --gen py hello.thrift
python_server.py
#!/usr/bin/env python
import sys
sys.path.append('./gen-py')
from hello import UserManager
from hello.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from daemon import runner
class UserManagerHandler:
def __init__(self):
pass
def ping(self):
print 'Welcome To Thrift...'
def get_user(self, firstname, lastname):
if firstname == '':
raise UserException(1, 'firstname is empty')
if lastname == '':
raise UserException(2, 'lastname is empty')
return lastname+' '+firstname+'!'
class App:
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/null'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/tmp123456.pid'
self.pidfile_timeout = 5
def run(self):
handler = UserManagerHandler()
processor = UserManager.Processor(handler)
transport = TSocket.TServerSocket(port=9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print 'Starting the server...'
server.serve()
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
php_client.php
#!/usr/bin/env php
<?php
$GLOBALS['THRIFT_ROOT'] = '/usr/lib/php';
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';
require_once './gen-php/hello/UserManager.php';
try {
$socket = new TSocket('localhost', 9090);
$transport = new TBufferedTransport($socket, 1024, 1024);
$protocol = new TBinaryProtocol($transport);
$client = new UserManagerClient($protocol);
$transport->open();
$client->ping();
printf("%s\n", $client->get_user('World', 'Hello'));
} catch (UserException $e) {
echo $e->error_msg;
}
测试
chmod a+x python_server.py
chmod a+x php_client.php
./python_server.py start
./php_client.php
Hello World!