设为首页 收藏本站
查看: 901|回复: 0

[经验分享] Apache Thrift学习小记

[复制链接]

尚未签到

发表于 2015-7-31 13:27:42 | 显示全部楼层 |阅读模式
http://blog.iyunv.com/images/authorship.gif  Apache Thrift学习小记 收藏   
         参考:
  http://incubator.apache.org/thrift/
  http://wiki.apache.org/thrift/FrontPage
  http://jnb.ociweb.com/jnb/jnbJun2009.html非常好的入门教程
  http://developers.facebook.com/thrift/thrift-20070401.pdfthrift开发者写的论文
  Thrift是个啥东东?
  来自wiki.apache.org/thrift/FrontPage的定义
  Thrift is a software framework for scalable cross-language services development.
  Thrift是为了实现跨语言服务访问的一个框架
  Thrift allows you to define data types and service interfaces in a simple definition file.
  Thrift定义了数据和服务的描述方式,是一种IDL
  Taking that file as input, the compiler generates code to be used to  easily build RPC clients and servers that communicate seamlessly across  programming languages.
  写一个定义文件,就可以使用thrift来生成某种语言RPC客户端和服务端程序框架。你只需要考虑如何实现你的服务就可以了。并且它支持很多种语言。
  这有点像web service, 定义好一个web service服务描述文件后,可以使用如axis等工具生成服务器端或客户端的框架程序。
  为什么还需要Thrift
  thrift-20070401.pdf中有解释。
  1、多语言开发的需要
  比如其中提到的搜索服务,LAMP本身没有这个功能,开发者可能使用C++开发,php如何访问这个服务呢?于是需要有一种高效的跨语言访问的方法。
  2、性能问题
  web service也可以实现多语言互访问的功能,但xml文件太大,性能不行。Thrift可以使用二进值的格式。
  开始测试
  实现一个简单的服务,就是根据loginName得到User, user中有userId,loginName, name, password
  第一步,写Thrift IDL文件 ,user.thrift,
  


view plaincopy to clipboardprint?

  • namespace java mytest.thrift.gen  
  • namespace py mytest.thrift  
  • struct User {  
  •   1: i32    userId,
  •   2: string loginName,  
  •   3: string password,  
  •   4: string name  
  • }
  • exception UserNotFound {
  •   1: string message  
  • }
  • service UserService {
  •   User getUser(1:string loginName) throws (1:UserNotFound unf),  
  •   list getUsers()
  • }
namespace java mytest.thrift.gen namespace py mytest.thrift struct User {   1: i32    userId,   2: string loginName,   3: string password,   4: string name } exception UserNotFound {   1: string message } service UserService {   User getUser(1:string loginName) throws (1:UserNotFound unf),   list getUsers() }      第二步,生成java和python代码
  thrift --gen java user.thrift
  thrift --gen py user.thrift
  第三步,实现java服务端
  参见:http://wiki.apache.org/thrift/ThriftUsageJava
  服务实现 UserServiceHandler.java
  


view plaincopy to clipboardprint?

  • package myserver;  
  • import java.util.ArrayList;  
  • import java.util.List;  
  • import mytest.thrift.gen.User;  
  • import mytest.thrift.gen.UserNotFound;  
  • import mytest.thrift.gen.UserService;  
  • import org.apache.thrift.TException;  
  • public class UserServiceHandler implements UserService.Iface {  
  •     @Override  
  •     public User getUser(String loginName) throws UserNotFound, TException {  
  •         if (!"login1".equals(loginName)) {  
  •             UserNotFound e = new UserNotFound("User not Found!");  
  •             throw e;  
  •         }
  •         User user = new User();  
  •         user.setUserId(100);  
  •         user.setLoginName("login1");  
  •         user.setPassword("pwd1");  
  •         user.setName("user1");  
  •         return user;  
  •     }
  •     @Override  
  •     public List getUsers() throws TException {  
  •         List list = new ArrayList();  
  •         User user = new User();  
  •         user.setUserId(100);  
  •         user.setLoginName("login1");  
  •         user.setPassword("pwd1");  
  •         user.setName("user1");  
  •         list.add(user);
  •         User user2 = new User();  
  •         user2.setUserId(200);  
  •         user2.setLoginName("login2");  
  •         user2.setPassword("pwd2");  
  •         user2.setName("user2");  
  •         list.add(user2);
  •         return list;  
  •     }
  • }
package myserver; import java.util.ArrayList; import java.util.List; import mytest.thrift.gen.User; import mytest.thrift.gen.UserNotFound; import mytest.thrift.gen.UserService; import org.apache.thrift.TException; public class UserServiceHandler implements UserService.Iface { @Override public User getUser(String loginName) throws UserNotFound, TException { if (!"login1".equals(loginName)) { UserNotFound e = new UserNotFound("User not Found!"); throw e; } User user = new User(); user.setUserId(100); user.setLoginName("login1"); user.setPassword("pwd1"); user.setName("user1"); return user; } @Override public List getUsers() throws TException { List list = new ArrayList(); User user = new User(); user.setUserId(100); user.setLoginName("login1"); user.setPassword("pwd1"); user.setName("user1"); list.add(user); User user2 = new User(); user2.setUserId(200); user2.setLoginName("login2"); user2.setPassword("pwd2"); user2.setName("user2"); list.add(user2); return list; } }

  主程序 Server.java
  


view plaincopy to clipboardprint?

  • package myserver;  
  • import mytest.thrift.gen.UserService;  
  • import org.apache.thrift.server.TServer;  
  • import org.apache.thrift.server.TSimpleServer;  
  • import org.apache.thrift.transport.TServerSocket;  
  • import org.apache.thrift.transport.TServerTransport;  
  • public class Server {  
  •     public static void main(String[] args) {  
  •         try {  
  •             UserServiceHandler handler = new UserServiceHandler();  
  •             UserService.Processor processor = new UserService.Processor(handler);  
  •             TServerTransport serverTransport = new TServerSocket(9090);  
  •             TServer server = new TSimpleServer(processor, serverTransport);  
  •             // Use this for a multithreaded server  
  •             // server = new TThreadPoolServer(processor, serverTransport);  
  •             System.out.println("Starting the server...");  
  •             server.serve();
  •         } catch (Exception x) {  
  •             x.printStackTrace();
  •         }
  •         System.out.println("done.");  
  •     }
  • }
package myserver; import mytest.thrift.gen.UserService; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; public class Server { public static void main(String[] args) { try { UserServiceHandler handler = new UserServiceHandler(); UserService.Processor processor = new UserService.Processor(handler); TServerTransport serverTransport = new TServerSocket(9090); TServer server = new TSimpleServer(processor, serverTransport); // Use this for a multithreaded server // server = new TThreadPoolServer(processor, serverTransport); System.out.println("Starting the server..."); server.serve(); } catch (Exception x) { x.printStackTrace(); } System.out.println("done."); } }  

  第四步,实现java客户端
  


view plaincopy to clipboardprint?

  • package myclient;  
  • import java.util.Iterator;  
  • import java.util.List;  
  • import mytest.thrift.gen.User;  
  • import mytest.thrift.gen.UserNotFound;  
  • import mytest.thrift.gen.UserService;  
  • 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;  
  • public class Client {  
  •     public static void main(String[] args) {  
  •         try {  
  •             TTransport transport = new TSocket("localhost", 9090);  
  •             TProtocol protocol = new TBinaryProtocol(transport);  
  •             UserService.Client client = new UserService.Client(protocol);  
  •             transport.open();
  •             System.out.println("test1");  
  •             try {  
  •                 User user1 = client.getUser("login1");  
  •                 System.out.println("name=" + user1.getName());  
  •             } catch (UserNotFound e) {  
  •                 System.out.println(e.getMessage());
  •             }

  •             System.out.println("test2");  
  •             try {  
  •                 User user2 = client.getUser("login10");  
  •                 System.out.println("name=" + user2.getName());  
  •             } catch (UserNotFound e) {  
  •                 System.out.println(e.getMessage());
  •             }

  •             System.out.println("test3");  
  •             List list = client.getUsers();
  •             Iterator it = list.iterator();
  •             while(it.hasNext()){  
  •                 User u = it.next();
  •                 System.out.println("name=" + u.getName());  
  •             }
  •             transport.close();
  •         } catch (TException x) {  
  •             x.printStackTrace();
  •         }
  •     }
  • }
package myclient; import java.util.Iterator; import java.util.List; import mytest.thrift.gen.User; import mytest.thrift.gen.UserNotFound; import mytest.thrift.gen.UserService; 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; public class Client { public static void main(String[] args) { try { TTransport transport = new TSocket("localhost", 9090); TProtocol protocol = new TBinaryProtocol(transport); UserService.Client client = new UserService.Client(protocol); transport.open(); System.out.println("test1"); try { User user1 = client.getUser("login1"); System.out.println("name=" + user1.getName()); } catch (UserNotFound e) { System.out.println(e.getMessage()); }  System.out.println("test2"); try { User user2 = client.getUser("login10"); System.out.println("name=" + user2.getName()); } catch (UserNotFound e) { System.out.println(e.getMessage()); }  System.out.println("test3"); List list = client.getUsers(); Iterator it = list.iterator(); while(it.hasNext()){ User u = it.next(); System.out.println("name=" + u.getName()); } transport.close(); } catch (TException x) { x.printStackTrace(); } } }     

第五步,实现python客户端


view plaincopy to clipboardprint?

  • from mytest.thrift import UserService  
  • from mytest.thrift.ttypes import UserNotFound
  • from thrift import Thrift
  • from thrift.transport import TSocket
  • from thrift.transport import TTransport
  • from thrift.protocol import TBinaryProtocol
  • try:  
  •     # Make socket  
  •     transport = TSocket.TSocket('localhost', 9090)  
  •     # Buffering is critical. Raw sockets are very slow  
  •     transport = TTransport.TBufferedTransport(transport)
  •     # Wrap in a protocol  
  •     protocol = TBinaryProtocol.TBinaryProtocol(transport)
  •     # Create a client to use the protocol encoder  
  •     client = UserService.Client(protocol)
  •     # Connect!  
  •     transport.open()
  •     try:   
  •         user1 = client.getUser("login1")  
  •         print user1.name
  •     except UserNotFound, io:
  •         print '%r' % io  
  •     # Close!  
  •     transport.close()
  • except Thrift.TException, tx:
  •     print '%s' % (tx.message)  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-92781-1-1.html 上篇帖子: 详解apache防盗链网站图片防盗链方法 下篇帖子: Lighttpd+Squid+Apache搭建高效率Web服务器[转]
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表