Thriftを使おう(2)
30分プログラム、その374。Thriftを使ってみよう、その2。
インストールについては、Thriftを使おう(1) - みずぴー日記を参照。
IDLを書こう
fact.thrift
service fact{
i32 fact(1: i32 n)
}
C++(サーバ)
fact_server.skelton.cppを適当に編集する。
class factHandler : virtual public factIf { public: factHandler() { // Your initialization goes here } int32_t fact(const int32_t n) { // Your implementation goes here if(n == 0){ return 1; }else{ return n * fact(n-1); } } };
さあ、コンパイルするぞ。ボクはインストール先が/opt/manual/thrift/なので、適当にそのへんをコマンドライン引数で与えてやる。
$ g++ fact.cpp fact_server.skeleton.cpp -o fact \ -lthrift -L/opt/manual/thrift/lib/ \ -I/opt/manual/thrift/include/thrift -I/opt/local/include/
Python(クライアント)
コードを書く前に、Python用のライブラリを入れてやる。
$ cd thrift $ cd lib/py $ make $ sudo make install
import thrift import thrift.transport.TSocket import thrift.protocol.TBinaryProtocol import fact.fact socket = thrift.transport.TSocket.TSocket('localhost',9090) protocol = thrift.protocol.TBinaryProtocol.TBinaryProtocol(socket) client = fact.fact.Client(protocol,protocol) socket.open() print client.fact(3) socket.close()
実行
$ ./gen-cpp/fact
$ cd gen-py $ python fact.py 6
できた!