MacでThriftを試してみる。

C++のプログラムをサーバにしてRubyのプログラムからAPIのように叩いてみたかったので、Thriftを試してみました。

Google先生に聞いてみるとCassandraのAPIを叩くときによく使うみたいだけど、シンプルな例が少なかったので自分用にメモしておきます。

はじめにソースからThriftをインストールしようとしたけど、Rspecに関するエラーが出たので断念してHomebrewでインストールしました。

バージョンはどちらも同じのよう。


・インストール

% brew update

# C++ Boostをインストール
% brew install boost

# Thriftをインストール
% brew install thrift

# 確認
% thrift -version
Thrift version 0.8.0


・定義ファイルを作成する

% mkdir thrift_test 
% cd thrift_test
% vi TinyCalc.thrift


・TinyCalc.thrift

#!/usr/local/bin/thrift

service TinyCalc
{
        double add(1: double param1, 2: double param2)
        double sub(1: double param1, 2: double param2)                          
}


・定義ファイルからコードを生成する

# サーバ(C++)とクライアント(Ruby)のコードを生成
% thrift --gen rb --gen cpp TinyCalc.thrift 


・サーバ(C++)プログラムを編集する

% cd gen-cpp

# テンプレートファイルをコピー、編集
% cp TinyCalc_server.skeleton.cpp TinyCalc_server.cpp
% vi TinyCalc_server.cpp

# コンパイル
% g++ -g TinyCalc_server.cpp TinyCalc.cpp -o TinyCal_server -lthrift -I/usr/local/include/thrift


・サーバプログラム

  double add(const double param1, const double param2) {
    return param1 + param2;
  }

  double sub(const double param1, const double param2) {
    return param1 - param2;                                                  
  }


・クライアント(Ruby)プログラムを作成する

# Gemでパッケージをインストール
% gem install thrift
% cd gem-rb
% vi tiny_calc_client.rb


・クライアントプログラム

$:.push('../gen-rb')                                                         

require 'thrift'
require 'tiny_calc'

begin
    transport = Thrift::BufferedTransport.new(Thrift::Socket.new('localhost', 9090))
    protocol = Thrift::BinaryProtocol.new(transport)
    client = TinyCalc::Client.new(protocol)

    transport.open()

    result1 = client.add(1.0, 5.0)
    result2 = client.sub(1.0, 5.0)

    p result1
    p result2

    transport.close()
rescue
    puts $!
end


・実行

# サーバ
% ./TinyCal_server

# クライアント
% ruby tiny_calc.rb
6.0
-4.0


とりあえず動作確認はできました。

これでC++でOpenCVとかをガリガリ走らせて、Rubyから叩くみたいなことができます。


[参考]
Apache Thrift を MacOS X 上で試す
Apache Thrift with Ruby – A basic Tutorial