install
mac
brew install thrift # thrift
gem install thrift # ruby
pip install thrift # python
example
注意:まずはPython2で試す
ほぼページ通りにやる
thriftファイルの定義
proj.thrift
# proj.thrift
namespace py demoserver
namespace rb demoserver
/* All operands are 32-bit integers called a Value */
typedef i32 Value
typedef i32 Result
/* Math service exposes an some math function */
service MyMath
{
Result add( 1: Value op1, 2: Value op2 ),
Result mul( 1: Value op1, 2: Value op2 ),
Result min( 1: Value op1, 2: Value op2 ),
Result max( 1: Value op1, 2: Value op2 )
}
RubyとPythonのファイルを作成
thrift --gen py proj.thrift
thrift --gen rb proj.thrift
server.pyを作成
この中で処理部分を書く
server.py
#!/usr/bin/python
import sys
sys.path.append('./gen-py')
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import demoserver.MyMath
class MathImpl( demoserver.MyMath.Iface ):
def add( self, op1, op2 ):
return op1 + op2
def mul( self, op1, op2 ):
return op1 * op2
def max( self, op1, op2 ):
return max([op1, op2])
def min( self, op1, op2 ):
return min([op1, op2])
if __name__ == '__main__':
processor = demoserver.MyMath.Processor( MathImpl() )
transport = TSocket.TServerSocket( port = 18181 )
tbfactory = TTransport.TBufferedTransportFactory()
pbfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TThreadedServer( processor, transport, tbfactory, pbfactory )
print('Starting the Math Server...')
server.serve();
rubyのclientを書く
client.rb
# Make thrift-generated code visible
$:.push('./gen-rb')
require 'thrift'
require 'my_math'
begin
# Build up the Thrift stack
transport = Thrift::BufferedTransport.new(Thrift::Socket.new('localhost', 18181))
protocol = Thrift::BinaryProtocol.new(transport)
client = Demoserver::MyMath::Client.new(protocol)
transport.open()
# Try an add operation
result = client.add( 1, 5 )
puts result.inspect
# Try a max operation
result = client.max( 9, 7 )
puts result.inspect
transport.close()
実行する
参考リンクの中の
python server.py
ruby client.rb
6 ## 1+5の答え
9 ## 9と7の最大値の答え