Thrift0.9.0の簡単な例では、javaはクライアント・サービス・エンドを実現します.
2855 ワード
前提として、Thrift-0.9がインストール.0、使用するjarパッケージ:
作成するthriftファイル
次のコマンドを実行します.
新しいjavaプロジェクトを作成し、Dディスクの下gen-javaの下のcomファイルをプロジェクトのsrcの下にコピーし、jarパッケージをインポートします.書類が間違っています.間違ったところを報告した@overrideを削除すればよい.
インタフェース実装コードとサービス側コードの作成:
クライアントコードの作成:
うんてん
libthrift-0.9.0.jar
log4j.1.2.14.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.5.8.jar
作成するthriftファイル
namespace java com.test
struct RS {
1:i32 code=0;
2:string id;
3:list<RRL> children;
4:string account
}
struct RRL {
1:string id;
2:string name;
2:string desc
}
service CWS {
RS getUserInfo(1:string name)
}
次のコマンドを実行します.
cd d:
thrift --gen java test.thrift
新しいjavaプロジェクトを作成し、Dディスクの下gen-javaの下のcomファイルをプロジェクトのsrcの下にコピーし、jarパッケージをインポートします.書類が間違っています.間違ったところを報告した@overrideを削除すればよい.
インタフェース実装コードとサービス側コードの作成:
public class CWSImpl implements CWS.Iface{
public RS getUserInfo(String name) throws TException{
if(name==null || name.equals("")){
return null;
}
RS rs = new RS();
rs.setCode(0);
rs.setId("1001");
}
public static void main(String[] args){
try{
CWSImpl handler = new CWSImpl();
CWS.Processor<CWSImpl> processor = new CWS.Processor<CWSImpl>(handler);
TServerTransport serverTransport = new TServerSocket(9000);
TServer server = new TSimpleServer(new TServer.Args(
serverTransport).processor(processor));
System.out.println("Starting server...");
server.serve();
} catch(Exception e){
e.printStackTrace();
}
}
}
クライアントコードの作成:
public class TestClient{
public static void main(String[] args){
try{
TTransport transport = new TSocket("localhost", 9000);
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
CWS.Client client = new CWS.Client(protocol);
System.out.println("client test: ");
RS rs = client.getUserInfo("tom");
System.out.println("code: " + rs.getCode() + ", id: " + rs.getId());
transport.close();
} catch (TException e) {
e.printStackTrace();
}
}
}
うんてん