惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

W
WeLiveSecurity
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
Stack Overflow Blog
Stack Overflow Blog
博客园 - 三生石上(FineUI控件)
T
Threat Research - Cisco Blogs
S
SegmentFault 最新的问题
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Proofpoint News Feed
J
Java Code Geeks
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
C
Cybersecurity and Infrastructure Security Agency CISA
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
U
Unit 42
腾讯CDC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
H
Help Net Security
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Heimdal Security Blog
博客园 - 聂微东
S
Securelist
大猫的无限游戏
大猫的无限游戏
Cloudbric
Cloudbric
Cisco Talos Blog
Cisco Talos Blog

博客园 - happy刘艺

关于SKILL idea解压包安装问题解决 转载:java :: Java中的双冒号操作符 转:Git的使用--如何将本地项目上传到Github(两种简单、方便的方法) 转:springboot 与swagger整合出现Unable to infer base url.This is common when using dynamic的解决办法 转:Swagger2自动生成接口文档和Mock模拟数据 InfluxDB springboot application.properties文件加载顺序 maven surefire插件与testng spring-boot项目学习路径 collection 与stream与lambd表达式的结合使用 转:Java中Lambda表达式的使用 class对象的getResource()方法 Eclipse开发,编译,打包常见问题总结------持续更新 mysql查找包含某个字符串的记录 性能测试入门(零)测试前言 性能测试入门(八)jmeter--PerfMon(性能监控工具)插件安装与部署 jmeter--PerfMon(性能监控工具)插件使用详解 性能测试入门(七)jmeter分布式测试
RPC之Thrift 介绍及java实例
happy刘艺 · 2019-05-07 · via 博客园 - happy刘艺

Thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 等等编程语言间无缝结合的、高效的服务。
Thrift最初由facebook开发,07年四月开放源码,08年5月进入apache孵化器。thrift允许你定义一个简单的定义文件中的数据类型和服务接口。以作为输入文件,编译器生成代码用来方便地生成RPC客户端和服务器通信的无缝跨编程语言。
官网地址:thrift.apache.org
推荐值得一看的文章:
http://jnb.ociweb.com/jnb/jnbJun2009.html
http://wiki.apache.org/thrift

http://thrift.apache.org/static/files/thrift-20070401.pdf

  • Thrift 基础架构

Thrift是一个服务端和客户端的架构体系,就是socket传输,Thrift 具有自己内部定义的传输协议规范(TProtocol)和传输数据标准(TTransports),通过IDL脚本对传输数据的数据结构(struct) 和传输数据的业务逻辑(service)根据不同的运行环境快速的构建相应的代码,并且通过自己内部的序列化机制对传输的数据进行简化和压缩提高高并发、 大型系统中数据交互的成本,下图描绘了Thrift的整体架构,分为6个部分:

1.你的业务逻辑实现(You Code) 

2.客户端和服务端对应的Service 

3.执行读写操作的计算结果

4.TProtocol 

5.TTransports  

6.底层I/O通信

  • Thrift 软件栈

  Thrift对软件栈的定义非常的清晰, 使得各个组件能够松散的耦合, 针对不同的应用场景, 选择不同是方式去搭建服务. 

评注:
  Transport: 传输层,定义数据传输方式,可以为TCP/IP传输,内存共享或者文件共享等
  protocol: 协议层, 定义数据传输格式,可以为二进制或者XML等
  Processor: 处理层, 这部分由定义的idl来生成, 封装了协议输入输出流, 并委托给用户实现的handler进行处理.
  Server: 服务层, 整合上述组件, 提供网络模型(单线程/多线程/事件驱动), 最终形成真正的服务.

  • Thrift脚本的数据类型

 * Base Types:基本类型
bool        Boolean, one byte
byte        Signed byte
i16         Signed 16-bit integer
i32         Signed 32-bit integer
i64         Signed 64-bit integer
double      64-bit floating point value
string      String
binary      Blob (byte array)

 * Struct:结构体类型
 * Container:容器类型,即List、Set、Map
map<t1,t2> Map from one type to another
list<t1>    Ordered list of one type
set<t1>     Set of unique elements of one type
 * Exception:异常类型
 * Service: 定义对象的接口,和一系列方法

  • 协议

  Thrift可以让你选择客户端与服务端之间传输通信协议的类别,在传输协议上总体上划分为文本(text)和二进制(binary)传输协议, 为节约带宽,提供传输效率,一般情况下使用二进制类型的传输协议为多数,但有时会还是会使用基于文本类型的协议,这需要根据项目/产品中的实际需求:
    * TBinaryProtocol – 二进制编码格式进行数据传输。
    * TCompactProtocol – 这种协议非常有效的,使用Variable-Length Quantity (VLQ) 编码对数据进行压缩。
    * TJSONProtocol – 使用JSON的数据编码协议进行数据传输。
    * TSimpleJSONProtocol – 这种节约只提供JSON只写的协议,适用于通过脚本语言解析
    * TDebugProtocol – 在开发的过程中帮助开发人员调试用的,以文本的形式展现方便阅读。

  • 传输层

    * TSocket- 使用堵塞式I/O进行传输,也是最常见的模式。
    * TFramedTransport- 使用非阻塞方式,按块的大小,进行传输,类似于Java中的NIO。
    * TFileTransport- 顾名思义按照文件的方式进程传输,虽然这种方式不提供Java的实现,但是实现起来非常简单。
    * TMemoryTransport- 使用内存I/O,就好比Java中的ByteArrayOutputStream实现。

    * TZlibTransport- 使用执行zlib压缩,不提供Java的实现。

  • Thrift 高性能网络服务模型

1). TServer类层次体系

TSimpleServer/TThreadPoolServer是阻塞服务模型
TNonblockingServer/THsHaServer/TThreadedSelectotServer是非阻塞服务模型(NIO)
2). TServer抽象类的定义
内部静态类Args的定义, 用于TServer类用于串联软件栈(传输层, 协议层, 处理层)

  1. public abstract class TServer {

  2.   

    public static class Args extends AbstractServerArgs<Args> {

  3.     

    public Args(TServerTransport transport) {

  4.   

    public static abstract class AbstractServerArgs<T extends AbstractServerArgs<T>> {

  5.     

    public AbstractServerArgs(TServerTransport transport);

  6.     

    public T processorFactory(TProcessorFactory factory);

  7.     

    public T processor(TProcessor processor);

  8.     

    public T transportFactory(TTransportFactory factory);

  9.     

    public T protocolFactory(TProtocolFactory factory);

TServer类定义的抽象类

  1. public abstract class TServer {

  2.   

    public abstract void serve();

  3.   

    public boolean isServing();

  4.   

    public void setServerEventHandler(TServerEventHandler eventHandler);

评注:抽象函数serve由具体的TServer实例来实现, 而并非所有的服务都需要优雅的退出, 因此stop没有被定义为抽象。

各种服务模型介绍如下:

    * TSimpleServer -  单线程服务器端使用标准的堵塞式I/O,只适合测试开发使用。抽象代码描述如下:

  1.   client = serverSocket.accept();

  2.   processor = factory.getProcess(client);

  3.     

    if ( !processor.process(input, output) ) {

    * TThreadPoolServer -  多线程服务器端使用标准的堵塞式I/O。引入了线程池,实现的模型是One Thread Per Connection。

线程池代码片段如下:

  1. private static ExecutorService createDefaultExecutorService(Args args) {

  2. SynchronousQueue<Runnable> executorQueue =

  3. new SynchronousQueue<Runnable>();

  4. return new ThreadPoolExecutor(args.minWorkerThreads,

采用同步队列(SynchronousQueue), 线程池采用能线程数可伸缩的模式. 

主线程循环:

  1.     TTransport client = serverTransport_.accept();

  2.     WorkerProcess wp = new WorkerProcess(client);

  3.     executorService_.execute(wp);

  4.   } catch (TTransportException ttx) {

   拆分了监听线程(accept)和处理客户端连接的工作线程(worker), 监听线程每接到一个客户端, 就投给线程池去处理. 这种模型能提高并发度, 但并发数取决于线程数, IO依旧阻塞, 从而限制该服务的服务能力。

   * TNonblockingServer – 采用NIO的模式, 借助Channel/Selector机制, 采用IO事件模型来处理。

  1.     Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();

  2.     

    while (!stopped_ && selectedKeys.hasNext()) {

  3.       SelectionKey key = selectedKeys.next();

  4.       

    if (key.isAcceptable()) {

  5.       } else if (key.isReadable()) {

  6.       } else if (key.isWritable()) {

  7.   } catch (IOException e) {

select代码里对accept/read/write等IO事件进行监控和处理, 唯一可惜的这个单线程处理. 当遇到handler里有阻塞的操作时, 会导致整个服务被阻塞住。
   *THsHaServer - 半同步半异步    

鉴于TNonblockingServer的缺点, THsHa引入了线程池去处理, 其模型把读写任务放到线程池去处理。HsHa是: Half-sync/Half-async的处理模式, Half-aysnc是在处理IO事件上(accept/read/write io), Half-sync用于handler对rpc的同步处理上.

   *TThreadedSelectorServer- 多线程服务器端使用非堵塞式I/O,是对以上NonblockingServer的扩充, 其分离了Accept和Read/Write的Selector线程, 同时引入Worker工作线程池. 它也是种Half-sync/Half-async的服务模型,也是最成熟,也是被业界所推崇的RPC服务模型。

 

MainReactor就是Accept线程, 用于监听客户端连接, SubReactor采用IO事件线程(多个), 主要负责对所有客户端的IO读写事件进行处理. 而Worker工作线程主要用于处理每个rpc请求的handler回调处理(这部分是同步的)。

  • Java简单实例

1.定义接口描述

创建Thrift文件HelloWorld.thrift,定义接口描述:

 namespace java cn.slimsmart.thrift.demo.helloworld
 service HelloWorld{ 
  string sayHello(1:string username)
 } 

2.生成java接口文件

thrift-0.9.2.exe -r -gen java ./HelloWorld.thrift

  1. package cn.slimsmart.thrift.demo.helloworld;

  2. import java.util.ArrayList;

  3. import java.util.Collections;

  4. import java.util.EnumMap;

  5. import java.util.EnumSet;

  6. import java.util.HashMap;

  7. import javax.annotation.Generated;

  8. import org.apache.thrift.TException;

  9. import org.apache.thrift.async.AsyncMethodCallback;

  10. import org.apache.thrift.protocol.TTupleProtocol;

  11. import org.apache.thrift.scheme.IScheme;

  12. import org.apache.thrift.scheme.SchemeFactory;

  13. import org.apache.thrift.scheme.StandardScheme;

  14. import org.apache.thrift.scheme.TupleScheme;

  15. import org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer;

  16. import org.slf4j.LoggerFactory;

  17. @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})

  18. @Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2015-2-28")

  19. public class HelloWorld {

  20. public String sayHello(String username) throws org.apache.thrift.TException;

  21. public interface AsyncIface {

  22. public void sayHello(String username, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;

  23. public static class Client extends org.apache.thrift.TServiceClient implements Iface {

  24. public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {

  25. public Client getClient(org.apache.thrift.protocol.TProtocol prot) {

  26. public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {

  27. return new Client(iprot, oprot);

  28. public Client(org.apache.thrift.protocol.TProtocol prot)

  29. public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {

  30. public String sayHello(String username) throws org.apache.thrift.TException

  31. public void send_sayHello(String username) throws org.apache.thrift.TException

  32. sayHello_args args = new sayHello_args();

  33. args.setUsername(username);

  34. sendBase("sayHello", args);

  35. public String recv_sayHello() throws org.apache.thrift.TException

  36. sayHello_result result = new sayHello_result();

  37. receiveBase(result, "sayHello");

  38. if (result.isSetSuccess()) {

  39. throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHello failed: unknown result");

  40. public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {

  41. public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {

  42. private org.apache.thrift.async.TAsyncClientManager clientManager;

  43. private org.apache.thrift.protocol.TProtocolFactory protocolFactory;

  44. public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {

  45. this.clientManager = clientManager;

  46. this.protocolFactory = protocolFactory;

  47. public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {

  48. return new AsyncClient(protocolFactory, clientManager, transport);

  49. public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {

  50. super(protocolFactory, clientManager, transport);

  51. public void sayHello(String username, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {

  52. sayHello_call method_call = new sayHello_call(username, resultHandler, this, ___protocolFactory, ___transport);

  53. this.___currentMethod = method_call;

  54. ___manager.call(method_call);

  55. public static class sayHello_call extends org.apache.thrift.async.TAsyncMethodCall {

  56. public sayHello_call(String username, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {

  57. super(client, protocolFactory, transport, resultHandler, false);

  58. this.username = username;

  59. public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {

  60. prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sayHello", org.apache.thrift.protocol.TMessageType.CALL, 0));

  61. sayHello_args args = new sayHello_args();

  62. args.setUsername(username);

  63. public String getResult() throws org.apache.thrift.TException {

  64. if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {

  65. throw new IllegalStateException("Method call not finished!");

  66. org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());

  67. org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);

  68. return (new Client(prot)).recv_sayHello();

  69. public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {

  70. public Processor(I iface) {

  71. super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));

  72. protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {

  73. super(iface, getProcessMap(processMap));

  74. private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {

  75. processMap.put("sayHello", new sayHello());

  76. public static class sayHello<I extends Iface> extends org.apache.thrift.ProcessFunction<I, sayHello_args> {

  77. public sayHello_args getEmptyArgsInstance() {

  78. return new sayHello_args();

  79. protected boolean isOneway() {

  80. public sayHello_result getResult(I iface, sayHello_args args) throws org.apache.thrift.TException {

  81. sayHello_result result = new sayHello_result();

  82. result.success = iface.sayHello(args.username);

  83. public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {

  84. private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());

  85. public AsyncProcessor(I iface) {

  86. super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));

  87. protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {

  88. super(iface, getProcessMap(processMap));

  89. private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {

  90. processMap.put("sayHello", new sayHello());

  91. public static class sayHello<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, sayHello_args, String> {

  92. public sayHello_args getEmptyArgsInstance() {

  93. return new sayHello_args();

  94. public AsyncMethodCallback<String> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {

  95. final org.apache.thrift.AsyncProcessFunction fcall = this;

  96. return new AsyncMethodCallback<String>() {

  97. public void onComplete(String o) {

  98. sayHello_result result = new sayHello_result();

  99. fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);

  100. LOGGER.error("Exception writing to internal frame buffer", e);

  101. public void onError(Exception e) {

  102. byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;

  103. org.apache.thrift.TBase msg;

  104. msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;

  105. msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());

  106. fcall.sendResponse(fb,msg,msgType,seqid);

  107. LOGGER.error("Exception writing to internal frame buffer", ex);

  108. protected boolean isOneway() {

  109. public void start(I iface, sayHello_args args, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws TException {

  110. iface.sayHello(args.username,resultHandler);

  111. public static class sayHello_args implements org.apache.thrift.TBase<sayHello_args, sayHello_args._Fields>, java.io.Serializable, Cloneable, Comparable<sayHello_args> {

  112. private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_args");

  113. private static final org.apache.thrift.protocol.TField USERNAME_FIELD_DESC = new org.apache.thrift.protocol.TField("username", org.apache.thrift.protocol.TType.STRING, (short)1);

  114. private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();

  115. schemes.put(StandardScheme.class, new sayHello_argsStandardSchemeFactory());

  116. schemes.put(TupleScheme.class, new sayHello_argsTupleSchemeFactory());

  117. public enum _Fields implements org.apache.thrift.TFieldIdEnum {

  118. USERNAME((short)1, "username");

  119. private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

  120. for (_Fields field : EnumSet.allOf(_Fields.class)) {

  121. byName.put(field.getFieldName(), field);

  122. public static _Fields findByThriftId(int fieldId) {

  123. public static _Fields findByThriftIdOrThrow(int fieldId) {

  124. _Fields fields = findByThriftId(fieldId);

  125. if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");

  126. public static _Fields findByName(String name) {

  127. private final short _thriftId;

  128. private final String _fieldName;

  129. _Fields(short thriftId, String fieldName) {

  130. public short getThriftFieldId() {

  131. public String getFieldName() {

  132. public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;

  133. Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);

  134. tmpMap.put(_Fields.USERNAME, new org.apache.thrift.meta_data.FieldMetaData("username", org.apache.thrift.TFieldRequirementType.DEFAULT,

  135. new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));

  136. metaDataMap = Collections.unmodifiableMap(tmpMap);

  137. org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_args.class, metaDataMap);

  138. this.username = username;

  139. public sayHello_args(sayHello_args other) {

  140. if (other.isSetUsername()) {

  141. this.username = other.username;

  142. public sayHello_args deepCopy() {

  143. return new sayHello_args(this);

  144. public String getUsername() {

  145. public sayHello_args setUsername(String username) {

  146. this.username = username;

  147. public void unsetUsername() {

  148. public boolean isSetUsername() {

  149. return this.username != null;

  150. public void setUsernameIsSet(boolean value) {

  151. public void setFieldValue(_Fields field, Object value) {

  152. setUsername((String)value);

  153. public Object getFieldValue(_Fields field) {

  154. throw new IllegalStateException();

  155. public boolean isSet(_Fields field) {

  156. throw new IllegalArgumentException();

  157. throw new IllegalStateException();

  158. public boolean equals(Object that) {

  159. if (that instanceof sayHello_args)

  160. return this.equals((sayHello_args)that);

  161. public boolean equals(sayHello_args that) {

  162. boolean this_present_username = true && this.isSetUsername();

  163. boolean that_present_username = true && that.isSetUsername();

  164. if (this_present_username || that_present_username) {

  165. if (!(this_present_username && that_present_username))

  166. if (!this.username.equals(that.username))

  167. List<Object> list = new ArrayList<Object>();

  168. boolean present_username = true && (isSetUsername());

  169. list.add(present_username);

  170. public int compareTo(sayHello_args other) {

  171. if (!getClass().equals(other.getClass())) {

  172. return getClass().getName().compareTo(other.getClass().getName());

  173. lastComparison = Boolean.valueOf(isSetUsername()).compareTo(other.isSetUsername());

  174. if (lastComparison != 0) {

  175. lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.username, other.username);

  176. if (lastComparison != 0) {

  177. public _Fields fieldForId(int fieldId) {

  178. return _Fields.findByThriftId(fieldId);

  179. public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {

  180. schemes.get(iprot.getScheme()).getScheme().read(iprot, this);

  181. public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {

  182. schemes.get(oprot.getScheme()).getScheme().write(oprot, this);

  183. public String toString() {

  184. StringBuilder sb = new StringBuilder("sayHello_args(");

  185. if (this.username == null) {

  186. sb.append(this.username);

  187. public void validate() throws org.apache.thrift.TException {

  188. private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {

  189. write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));

  190. } catch (org.apache.thrift.TException te) {

  191. throw new java.io.IOException(te);

  192. private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {

  193. read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));

  194. } catch (org.apache.thrift.TException te) {

  195. throw new java.io.IOException(te);

  196. private static class sayHello_argsStandardSchemeFactory implements SchemeFactory {

  197. public sayHello_argsStandardScheme getScheme() {

  198. return new sayHello_argsStandardScheme();

  199. private static class sayHello_argsStandardScheme extends StandardScheme<sayHello_args> {

  200. public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_args struct) throws org.apache.thrift.TException {

  201. org.apache.thrift.protocol.TField schemeField;

  202. schemeField = iprot.readFieldBegin();

  203. if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {

  204. switch (schemeField.id) {

  205. if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {

  206. struct.username = iprot.readString();

  207. struct.setUsernameIsSet(true);

  208. org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);

  209. org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);

  210. public void write(org.apache.thrift.protocol.TProtocol oprot, sayHello_args struct) throws org.apache.thrift.TException {

  211. oprot.writeStructBegin(STRUCT_DESC);

  212. if (struct.username != null) {

  213. oprot.writeFieldBegin(USERNAME_FIELD_DESC);

  214. oprot.writeString(struct.username);

  215. private static class sayHello_argsTupleSchemeFactory implements SchemeFactory {

  216. public sayHello_argsTupleScheme getScheme() {

  217. return new sayHello_argsTupleScheme();

  218. private static class sayHello_argsTupleScheme extends TupleScheme<sayHello_args> {

  219. public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException {

  220. TTupleProtocol oprot = (TTupleProtocol) prot;

  221. BitSet optionals = new BitSet();

  222. if (struct.isSetUsername()) {

  223. oprot.writeBitSet(optionals, 1);

  224. if (struct.isSetUsername()) {

  225. oprot.writeString(struct.username);

  226. public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException {

  227. TTupleProtocol iprot = (TTupleProtocol) prot;

  228. BitSet incoming = iprot.readBitSet(1);

  229. struct.username = iprot.readString();

  230. struct.setUsernameIsSet(true);

  231. public static class sayHello_result implements org.apache.thrift.TBase<sayHello_result, sayHello_result._Fields>, java.io.Serializable, Cloneable, Comparable<sayHello_result> {

  232. private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_result");

  233. private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0);

  234. private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();

  235. schemes.put(StandardScheme.class, new sayHello_resultStandardSchemeFactory());

  236. schemes.put(TupleScheme.class, new sayHello_resultTupleSchemeFactory());

  237. public enum _Fields implements org.apache.thrift.TFieldIdEnum {

  238. SUCCESS((short)0, "success");

  239. private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

  240. for (_Fields field : EnumSet.allOf(_Fields.class)) {

  241. byName.put(field.getFieldName(), field);

  242. public static _Fields findByThriftId(int fieldId) {

  243. public static _Fields findByThriftIdOrThrow(int fieldId) {

  244. _Fields fields = findByThriftId(fieldId);

  245. if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");

  246. public static _Fields findByName(String name) {

  247. private final short _thriftId;

  248. private final String _fieldName;

  249. _Fields(short thriftId, String fieldName) {

  250. public short getThriftFieldId() {

  251. public String getFieldName() {

  252. public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;

  253. Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);

  254. tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,

  255. new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));

  256. metaDataMap = Collections.unmodifiableMap(tmpMap);

  257. org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_result.class, metaDataMap);

  258. public sayHello_result() {

  259. public sayHello_result(sayHello_result other) {

  260. if (other.isSetSuccess()) {

  261. this.success = other.success;

  262. public sayHello_result deepCopy() {

  263. return new sayHello_result(this);

  264. public String getSuccess() {

  265. public sayHello_result setSuccess(String success) {

  266. public void unsetSuccess() {

  267. public boolean isSetSuccess() {

  268. return this.success != null;

  269. public void setSuccessIsSet(boolean value) {

  270. public void setFieldValue(_Fields field, Object value) {

  271. setSuccess((String)value);

  272. public Object getFieldValue(_Fields field) {

  273. throw new IllegalStateException();

  274. public boolean isSet(_Fields field) {

  275. throw new IllegalArgumentException();

  276. throw new IllegalStateException();

  277. public boolean equals(Object that) {

  278. if (that instanceof sayHello_result)

  279. return this.equals((sayHello_result)that);

  280. public boolean equals(sayHello_result that) {

  281. boolean this_present_success = true && this.isSetSuccess();

  282. boolean that_present_success = true && that.isSetSuccess();

  283. if (this_present_success || that_present_success) {

  284. if (!(this_present_success && that_present_success))

  285. if (!this.success.equals(that.success))

  286. List<Object> list = new ArrayList<Object>();

  287. boolean present_success = true && (isSetSuccess());

  288. list.add(present_success);

  289. public int compareTo(sayHello_result other) {

  290. if (!getClass().equals(other.getClass())) {

  291. return getClass().getName().compareTo(other.getClass().getName());

  292. lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());

  293. if (lastComparison != 0) {

  294. lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);

  295. if (lastComparison != 0) {

  296. public _Fields fieldForId(int fieldId) {

  297. return _Fields.findByThriftId(fieldId);

  298. public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {

  299. schemes.get(iprot.getScheme()).getScheme().read(iprot, this);

  300. public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {

  301. schemes.get(oprot.getScheme()).getScheme().write(oprot, this);

  302. public String toString() {

  303. StringBuilder sb = new StringBuilder("sayHello_result(");

  304. if (this.success == null) {

  305. public void validate() throws org.apache.thrift.TException {

  306. private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {

  307. write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));

  308. } catch (org.apache.thrift.TException te) {

  309. throw new java.io.IOException(te);

  310. private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {

  311. read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));

  312. } catch (org.apache.thrift.TException te) {

  313. throw new java.io.IOException(te);

  314. private static class sayHello_resultStandardSchemeFactory implements SchemeFactory {

  315. public sayHello_resultStandardScheme getScheme() {

  316. return new sayHello_resultStandardScheme();

  317. private static class sayHello_resultStandardScheme extends StandardScheme<sayHello_result> {

  318. public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_result struct) throws org.apache.thrift.TException {

  319. org.apache.thrift.protocol.TField schemeField;

  320. schemeField = iprot.readFieldBegin();

  321. if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {

  322. switch (schemeField.id) {

  323. if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {

  324. struct.success = iprot.readString();

  325. struct.setSuccessIsSet(true);

  326. org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);

  327. org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);

  328. public void write(org.apache.thrift.protocol.TProtocol oprot, sayHello_result struct) throws org.apache.thrift.TException {

  329. oprot.writeStructBegin(STRUCT_DESC);

  330. if (struct.success != null) {

  331. oprot.writeFieldBegin(SUCCESS_FIELD_DESC);

  332. oprot.writeString(struct.success);

  333. private static class sayHello_resultTupleSchemeFactory implements SchemeFactory {

  334. public sayHello_resultTupleScheme getScheme() {

  335. return new sayHello_resultTupleScheme();

  336. private static class sayHello_resultTupleScheme extends TupleScheme<sayHello_result> {

  337. public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException {

  338. TTupleProtocol oprot = (TTupleProtocol) prot;

  339. BitSet optionals = new BitSet();

  340. if (struct.isSetSuccess()) {

  341. oprot.writeBitSet(optionals, 1);

  342. if (struct.isSetSuccess()) {

  343. oprot.writeString(struct.success);

  344. public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException {

  345. TTupleProtocol iprot = (TTupleProtocol) prot;

  346. BitSet incoming = iprot.readBitSet(1);

  347. struct.success = iprot.readString();

  348. struct.setSuccessIsSet(true);

将生成的接口HelloWorld.java复制到java工程下.

在pom.xml导入依赖jar包:

  1. <groupId>org.apache.thrift</groupId>

  2. <artifactId>libthrift</artifactId>

  3. <groupId>org.slf4j</groupId>

  4. <artifactId>slf4j-log4j12</artifactId>

3.接口实现类

接口实现类HelloWorldImpl.java:

  1. package cn.slimsmart.thrift.demo.helloworld;

  2. import org.apache.thrift.TException;

  3. public class HelloWorldImpl implements HelloWorld.Iface{

  4. public String sayHello(String username) throws TException {

  5. return "hello world, "+username;

4.服务器端

服务端启动类HelloTSimpleServer.java:

  1. package cn.slimsmart.thrift.demo.helloworld;

  2. import org.apache.thrift.TException;

  3. import org.apache.thrift.TProcessor;

  4. import org.apache.thrift.protocol.TBinaryProtocol;

  5. import org.apache.thrift.server.TServer;

  6. import org.apache.thrift.server.TSimpleServer;

  7. import org.apache.thrift.transport.TServerSocket;

  8. public class HelloTSimpleServer {

  9. public static final int SERVER_PORT = 8080;

  10. public static void main(String[] args) throws TException {

  11. TProcessor tprocessor = new HelloWorld.Processor<HelloWorld.Iface>(new HelloWorldImpl());

  12. TServerSocket serverTransport = new TServerSocket(SERVER_PORT);

  13. TServer.Args tArgs = new TServer.Args(serverTransport);

  14. tArgs.processor(tprocessor);

  15. tArgs.protocolFactory(new TBinaryProtocol.Factory());

  16. TServer server = new TSimpleServer(tArgs);

  17. System.out.println("HelloServer start....");

5.客户端

客户端调用类HelloClient.java:

  1. package cn.slimsmart.thrift.demo.helloworld;

  2. import org.apache.thrift.TException;

  3. import org.apache.thrift.protocol.TBinaryProtocol;

  4. import org.apache.thrift.protocol.TProtocol;

  5. import org.apache.thrift.transport.TSocket;

  6. import org.apache.thrift.transport.TTransport;

  7. public class HelloClient {

  8. public static final String SERVER_IP = "127.0.0.1";

  9. public static final int SERVER_PORT = 8080;

  10. public static final int TIMEOUT = 30000;

  11. public static void main(String[] args) throws TException {

  12. TTransport transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);

  13. TProtocol protocol = new TBinaryProtocol(transport);

  14. HelloWorld.Client client = new HelloWorld.Client(protocol);

  15. String result = client.sayHello("jack");

  16. System.out.println("result : " + result);

先运行服务端,再运行客户端,看一下运行结果吧。