google了很多thrift的教程,但是都沒有一個詳細的hello 的demo。
最終自己慢慢摸索出來。
客戶端用的php,服務器端用的pyhton,紀錄下第一次使用thrift的全過程。
需要了解的知識:
1 composer自動價值類
2 php命名空間(類似java裏面的package)
3 laravel
先貼代碼:
thrift文件代碼
namespace php zeu
service HelloWorld {
string sayHello()
}
服務器端代碼:
import sys
sys.path.append('../gen-py')
from helloworld import HelloWorld
from helloworld.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import socket
class HelloWorldHandler:
def __init__(self):
self.log = {}
def sayHello(self):
print "sayHello()"
return "hello leiminglin"
handler = HelloWorldHandler()
processor = HelloWorld.Processor(handler)
transport = TSocket.TServerSocket('127.0.0.1',12345)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print "Starting python server"
server.serve()
客戶端代碼:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Thrift\Transport\TSocket;
use Thrift\Transport\TTransport;
use Thrift\Exception\TException;
use Thrift\Exception\TTransportException;
use Thrift\Factory\TStringFuncFactory;
use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TBufferedTransport;
use zeu\HelloWorldClient;
class UserController extends Controller {
public function test(){
$host = "127.0.0.1";
$port = 12345;
try {
//Thrift connection handling
$socket = new TSocket( $host , $port );
$transport = new TBufferedTransport($socket, 1024, 1024);
$protocol = new TBinaryProtocol($transport);
// get our example client
$client = new HelloWorldClient($protocol);
$transport->open();
// Get current timestamp from server
$return = $client->sayHello();
echo $return;
$transport->close();
} catch (TException $tx) {
print 'Something went wrong: '.$tx->getMessage()."\n";
}
}
}
服務器文件和客戶端文件目錄位沒有任何關係,不需要在同一個目錄下面。
所以我對php文件放在我laravel框架裏面,python文件放在~/cg/thriftTest目錄下面。
服務器處的重點是找到thrift-0.9.*裏面py目錄下lib的目錄,import進去。或者複製到當前目錄下也可以。
客戶端處的重點也是找到thrift-0.9.*裏面py目錄下lib的目錄,import進去。或者複製到當前目錄下也可以。
我都是複製的。
將thrift-0.9.*裏面php目錄下lib的目錄,複製到laravel跟目錄下面,文件名爲thrift.
用composer自動加載
“autoload-dev”: {
“classmap”: [
“tests/TestCase.php”,
“app/http/controllers”,
“app/models”,
“Thrift”,
“cg/thrift/zeu”
]
},
composer dump-autoload –optimize 安裝包的時候可以同樣使用–optimize-autoloader。不加這一選項,你可能會發現20%到25%的性能損失。
從瀏覽器運行即可看到結果。