読者です 読者をやめる 読者になる 読者になる

Thriftを試す

Thrift

PythonでServer、PerlでClientを書く。

検討事項。

  • gearmanとどちらが信頼できるか
  • perl Clientを使う時のnamespaceとservice名の定義の仕方
    • namespaceとservice名を統一して、HelloWorld.pmとHelloWord::Types.pmのようにするのが無難か?
  • thriftファイルを編集するときのemacsモードが欲しい

インターフェイスの定義

/* helloworld.thrift */
namespace perl HelloWorld

service HelloWorldWorker {
  i32 work(1: string data),
  async void work_async(1: string data)
}
$ thrift --gen perl --gen py:new_style -r helloworld.thift

Server

#!/usr/bin/env python
import sys
sys.path.append('/path/to/gen-py')

from helloworld import HelloWorldWorker
from helloworld.ttypes import *

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

class HelloWorldWorkerHandler(object):
    def work(self, data):
        print "work", data, type(data)
        return len(data)

    def work_async(self, data):
        print "work_async", data

handler = HelloWorldWorkerHandler()
processor = HelloWorldWorker.Processor(handler)
transport = TSocket.TServerSocket(9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
server.serve()

Client

#!/usr/bin/perl
use strict;
use warnings;

use lib '/path/to/gen-perl';

use Thrift;
use Thrift::BinaryProtocol;
use Thrift::Socket;
use Thrift::BufferedTransport;

use HelloWorldWorker;
use HelloWorld::Types;

use Data::Dumper;

my $socket    = Thrift::Socket->new('localhost', 9090);
my $transport = Thrift::BufferedTransport->new($socket, 1024, 1024);
my $protocol  = Thrift::BinaryProtocol->new($transport);
my $client    = HelloWorldWorkerClient->new($protocol);

eval{
    $transport->open();

    my $res = $client->work("spam egg ham");
    print Dumper($res);
    # $VAR1 = 12;

    $res = $client->work_async("SPAM EGG HAM");
    print Dumper($res);
    # $VAR1 = '0 but true';

    $transport->close();

};
if($@){
    warn Dumper($@);
}