手机版
你好,游客 登录 注册
背景:
阅读新闻

使用Java快速入门Thrift

[日期:2012-07-11] 来源:oschina  作者:王振威 [字体:大 中 小]

写一个 service handler

Service handler 类必须实现 AdditionService.Iface接口。

示例Service handler(AdditionServiceHandler.Java)

package com.eviac.blog.samples.thrift.server; 
 
import org.apache.thrift.TException; 
 
public class AdditionServiceHandler implements AdditionService.Iface { 
 
 @Override 
 public int add(int n1, int n2) throws TException { 
  return n1 + n2; 
 } 
 
}

写一个简单的服务器
下面的示例代码是一个简单的Thrift服务器。可以看到下面的代码中有一段是注释了的,可以去掉注释来启用多线程服务器。
示例服务器(MyServer.java)

package com.eviac.blog.samples.thrift.server; 
 
import org.apache.thrift.transport.TServerSocket; 
import org.apache.thrift.transport.TServerTransport; 
import org.apache.thrift.server.TServer; 
import org.apache.thrift.server.TServer.Args; 
import org.apache.thrift.server.TSimpleServer; 
 
public class MyServer { 
 
 public static void StartsimpleServer(AdditionService.Processor<AdditionServiceHandler> processor) { 
  try { 
   TServerTransport serverTransport = new TServerSocket(9090); 
   TServer server = new TSimpleServer( 
     new Args(serverTransport).processor(processor)); 
 
   // Use this for a multithreaded server 
   // TServer server = new TThreadPoolServer(new 
   // TThreadPoolServer.Args(serverTransport).processor(processor)); 
 
   System.out.println("Starting the simple server..."); 
   server.serve(); 
  } catch (Exception e) { 
   e.printStackTrace(); 
  } 
 } 
  
 public static void main(String[] args) { 
  StartsimpleServer(new AdditionService.Processor<AdditionServiceHandler>(new AdditionServiceHandler())); 
 } 
 
}

写一个客户端
下面的例子是一个使用Java写的客户端短使用AdditionService的服务。

package com.eviac.blog.samples.thrift.client; 
 
import org.apache.thrift.TException; 
import org.apache.thrift.protocol.TBinaryProtocol; 
import org.apache.thrift.protocol.TProtocol; 
import org.apache.thrift.transport.TSocket; 
import org.apache.thrift.transport.TTransport; 
import org.apache.thrift.transport.TTransportException; 
 
public class AdditionClient { 
 
 public static void main(String[] args) { 
 
  try { 
   TTransport transport; 
 
   transport = new TSocket("localhost", 9090); 
   transport.open(); 
 
   TProtocol protocol = new TBinaryProtocol(transport); 
   AdditionService.Client client = new AdditionService.Client(protocol); 
 
   System.out.println(client.add(100, 200)); 
 
   transport.close(); 
  } catch (TTransportException e) { 
   e.printStackTrace(); 
  } catch (TException x) { 
   x.printStackTrace(); 
  } 
 } 
 
}

运行服务端代码(MyServer.java)将会看到下面的输出。

Starting the simple server...

然后运行客户端代码(AdditionClient.java),将会看到如下输出。

300

linux
相关资讯       Java教程  Thrift 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款