今回は碧(midori)でThriftを使う簡単なサンプルです。
サーバ側とクライアント側をそれぞれ解説します。
まずは必要なものをダウンロードします。
●Thrift compiler for Windows (thrift-0.5.0.exe)
http://thrift.apache.org/download/●SLF4Jのバイナリ
http://www.slf4j.org/download.html現在のバージョンは1.6.1。
[手順]
■最初にチュートリアルのプロジェクトを以下のURLからダウンロード。
http://midori.googlecode.com/files/midoriTutorial-1.0.0.zip■次にプロジェクトをEclipseでインポート。
■適当な場所に「IHelloService.thrift」という名前で以下のファイルを作成する。
[ファイルの中身]
namespace java tutorial.service
service IHelloService
{
string hello(1:string name)
}
■「thrift-0.5.0.exe」と「IHelloService.thrift」を同じフォルダに格納し、
コマンドプロンプトから以下のコマンドを実行
[コマンド]
thrift-0.5.0.exe --gen java IHelloService.thrift
■生成されたgen-java\tutorial\serviceフォルダのIHelloService.javaを
src\tutorial\serviceにコピー。
■コンパイルエラーが出るので、SLF4Jのアーカイブの中から「slf4j-api-1.6.1.jar」と
「slf4j-log4j12-1.6.1.jar」をWEB-INF\libにコピーしてビルドパスに追加。
■src\tutorial\serviceに実装クラス(HelloService.java)を作成する。
[ソースコード]
package tutorial.service;
import org.apache.thrift.TException;
import jp.fores.midori.server.annotation.RPCService;
@RPCService
public class HelloService implements IHelloService.Iface {
@Override
public String hello(String name) throws TException {
return "Hello, " + name;
}
}
■src\testにテスト用のメインクラスを作成する
[ソースコード]
package test;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.THttpClient;
import org.apache.thrift.transport.TTransport;
import tutorial.service.IHelloService;
public class TestClient {
public static void main(String[] args) {
TTransport transport = null;
try {
//クライアントの作成
transport = new THttpClient("http://localhost:8080/midoriTutorial/rpc/helloService.thrift");
TProtocol protocol = new TBinaryProtocol(transport);
IHelloService.Client client = new IHelloService.Client(protocol);
//接続開始
transport.open();
//RPC呼び出し
System.out.println(client.hello("テスト"));
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (transport != null) {
//接続終了
transport.close();
}
}
}
}
■Tomcatを起動してから先ほどのテスト用のメインクラス(TestClient)を
実行するとコンソールに結果が表示されます。
[コンソール表示]
Hello, テスト
■以前書いた「碧(midori)のクライアントを色んな言語・方式で実装しRPC呼び出し」で呼び出すこともできます。
ServletでThirftのサーバ側を実装する場合はTServletを継承したクラスを
実装する必要がありますが、midoriを使う場合はプラグインが
その処理を行うので必要ありません。
そういう意味では比較的簡単にThirftを使うことが出来ます!