前面七篇文章分析了Thrfit的方方面面,看到这里时应该对Thrift有了深入的理解。

Thrift源代码分析(一)-- 基本概念

Thrift源代码分析(二)-- 协议和编解码

Thrift源代码分析(三)-- IDL和生成代码分析

Thrift源代码分析(四)-- 方法调用模型分析

Thrift源代码分析(五)-- FrameBuffer类分析

Thrift源代码分析(六)-- Transport传输层分析

Thrift源代码分析(七)-- TServerserver分析

以下通过一个实际能够执行的样例来跑一跑Thrift,结束这个主题

1. 通过IDL来定义接口:   DemoService.thrift

  1. namespace java com.thrift.test
  2.  
  3. service DemoService{
  4. string sayHi(1:string name);
  5. }

2. 依据IDL自己主动生成代码

  1. thrift -r --gen java DemoService.thrift

3. 生成的代码供server和client调用

  1. /**
  2. * Autogenerated by Thrift Compiler (0.8.0)
  3. *
  4. * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
  5. * @generated
  6. */
  7. package com.thrift.test;
  8.  
  9. import org.apache.thrift.scheme.IScheme;
  10. import org.apache.thrift.scheme.SchemeFactory;
  11. import org.apache.thrift.scheme.StandardScheme;
  12.  
  13. import org.apache.thrift.scheme.TupleScheme;
  14. import org.apache.thrift.protocol.TTupleProtocol;
  15. import java.util.List;
  16. import java.util.ArrayList;
  17. import java.util.Map;
  18. import java.util.HashMap;
  19. import java.util.EnumMap;
  20. import java.util.Set;
  21. import java.util.HashSet;
  22. import java.util.EnumSet;
  23. import java.util.Collections;
  24. import java.util.BitSet;
  25. import java.nio.ByteBuffer;
  26. import java.util.Arrays;
  27. import org.slf4j.Logger;
  28. import org.slf4j.LoggerFactory;
  29.  
  30. public class DemoService {
  31.  
  32. public interface Iface {
  33.  
  34. public String sayHi(String name) throws org.apache.thrift.TException;
  35.  
  36. }
  37.  
  38. public interface AsyncIface {
  39.  
  40. public void sayHi(String name, org.apache.thrift.async.AsyncMethodCallback<AsyncClient.sayHi_call> resultHandler) throws org.apache.thrift.TException;
  41.  
  42. }
  43.  
  44. public static class Client extends org.apache.thrift.TServiceClient implements Iface {
  45. public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
  46. public Factory() {}
  47. public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
  48. return new Client(prot);
  49. }
  50. public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
  51. return new Client(iprot, oprot);
  52. }
  53. }
  54.  
  55. public Client(org.apache.thrift.protocol.TProtocol prot)
  56. {
  57. super(prot, prot);
  58. }
  59.  
  60. public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
  61. super(iprot, oprot);
  62. }
  63.  
  64. public String sayHi(String name) throws org.apache.thrift.TException
  65. {
  66. send_sayHi(name);
  67. return recv_sayHi();
  68. }
  69.  
  70. public void send_sayHi(String name) throws org.apache.thrift.TException
  71. {
  72. sayHi_args args = new sayHi_args();
  73. args.setName(name);
  74. sendBase("sayHi", args);
  75. }
  76.  
  77. public String recv_sayHi() throws org.apache.thrift.TException
  78. {
  79. sayHi_result result = new sayHi_result();
  80. receiveBase(result, "sayHi");
  81. if (result.isSetSuccess()) {
  82. return result.success;
  83. }
  84. throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHi failed: unknown result");
  85. }
  86.  
  87. }
  88. public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
  89. public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
  90. private org.apache.thrift.async.TAsyncClientManager clientManager;
  91. private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
  92. public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
  93. this.clientManager = clientManager;
  94. this.protocolFactory = protocolFactory;
  95. }
  96. public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
  97. return new AsyncClient(protocolFactory, clientManager, transport);
  98. }
  99. }
  100.  
  101. public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
  102. super(protocolFactory, clientManager, transport);
  103. }
  104.  
  105. public void sayHi(String name, org.apache.thrift.async.AsyncMethodCallback<sayHi_call> resultHandler) throws org.apache.thrift.TException {
  106. checkReady();
  107. sayHi_call method_call = new sayHi_call(name, resultHandler, this, ___protocolFactory, ___transport);
  108. this.___currentMethod = method_call;
  109. ___manager.call(method_call);
  110. }
  111.  
  112. public static class sayHi_call extends org.apache.thrift.async.TAsyncMethodCall {
  113. private String name;
  114. public sayHi_call(String name, org.apache.thrift.async.AsyncMethodCallback<sayHi_call> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
  115. super(client, protocolFactory, transport, resultHandler, false);
  116. this.name = name;
  117. }
  118.  
  119. public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
  120. prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sayHi", org.apache.thrift.protocol.TMessageType.CALL, 0));
  121. sayHi_args args = new sayHi_args();
  122. args.setName(name);
  123. args.write(prot);
  124. prot.writeMessageEnd();
  125. }
  126.  
  127. public String getResult() throws org.apache.thrift.TException {
  128. if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
  129. throw new IllegalStateException("Method call not finished!");
  130. }
  131. org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
  132. org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
  133. return (new Client(prot)).recv_sayHi();
  134. }
  135. }
  136.  
  137. }
  138.  
  139. public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
  140. private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());
  141. public Processor(I iface) {
  142. super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
  143. }
  144.  
  145. protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
  146. super(iface, getProcessMap(processMap));
  147. }
  148.  
  149. private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ?
  150.  
  151. extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
  152. processMap.put("sayHi", new sayHi());
  153. return processMap;
  154. }
  155.  
  156. private static class sayHi<I extends Iface> extends org.apache.thrift.ProcessFunction<I, sayHi_args> {
  157. public sayHi() {
  158. super("sayHi");
  159. }
  160.  
  161. protected sayHi_args getEmptyArgsInstance() {
  162. return new sayHi_args();
  163. }
  164.  
  165. protected sayHi_result getResult(I iface, sayHi_args args) throws org.apache.thrift.TException {
  166. sayHi_result result = new sayHi_result();
  167. result.success = iface.sayHi(args.name);
  168. return result;
  169. }
  170. }
  171.  
  172. }
  173.  
  174. public static class sayHi_args implements org.apache.thrift.TBase<sayHi_args, sayHi_args._Fields>, java.io.Serializable, Cloneable {
  175. private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHi_args");
  176.  
  177. private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1);
  178.  
  179. private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  180. static {
  181. schemes.put(StandardScheme.class, new sayHi_argsStandardSchemeFactory());
  182. schemes.put(TupleScheme.class, new sayHi_argsTupleSchemeFactory());
  183. }
  184.  
  185. public String name; // required
  186.  
  187. /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  188. public enum _Fields implements org.apache.thrift.TFieldIdEnum {
  189. NAME((short)1, "name");
  190.  
  191. private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
  192.  
  193. static {
  194. for (_Fields field : EnumSet.allOf(_Fields.class)) {
  195. byName.put(field.getFieldName(), field);
  196. }
  197. }
  198.  
  199. /**
  200. * Find the _Fields constant that matches fieldId, or null if its not found.
  201. */
  202. public static _Fields findByThriftId(int fieldId) {
  203. switch(fieldId) {
  204. case 1: // NAME
  205. return NAME;
  206. default:
  207. return null;
  208. }
  209. }
  210.  
  211. /**
  212. * Find the _Fields constant that matches fieldId, throwing an exception
  213. * if it is not found.
  214. */
  215. public static _Fields findByThriftIdOrThrow(int fieldId) {
  216. _Fields fields = findByThriftId(fieldId);
  217. if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
  218. return fields;
  219. }
  220.  
  221. /**
  222. * Find the _Fields constant that matches name, or null if its not found.
  223. */
  224. public static _Fields findByName(String name) {
  225. return byName.get(name);
  226. }
  227.  
  228. private final short _thriftId;
  229. private final String _fieldName;
  230.  
  231. _Fields(short thriftId, String fieldName) {
  232. _thriftId = thriftId;
  233. _fieldName = fieldName;
  234. }
  235.  
  236. public short getThriftFieldId() {
  237. return _thriftId;
  238. }
  239.  
  240. public String getFieldName() {
  241. return _fieldName;
  242. }
  243. }
  244.  
  245. // isset id assignments
  246. public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  247. static {
  248. Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
  249. tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT,
  250. new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
  251. metaDataMap = Collections.unmodifiableMap(tmpMap);
  252. org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHi_args.class, metaDataMap);
  253. }
  254.  
  255. public sayHi_args() {
  256. }
  257.  
  258. public sayHi_args(
  259. String name)
  260. {
  261. this();
  262. this.name = name;
  263. }
  264.  
  265. /**
  266. * Performs a deep copy on <i>other</i>.
  267. */
  268. public sayHi_args(sayHi_args other) {
  269. if (other.isSetName()) {
  270. this.name = other.name;
  271. }
  272. }
  273.  
  274. public sayHi_args deepCopy() {
  275. return new sayHi_args(this);
  276. }
  277.  
  278. @Override
  279. public void clear() {
  280. this.name = null;
  281. }
  282.  
  283. public String getName() {
  284. return this.name;
  285. }
  286.  
  287. public sayHi_args setName(String name) {
  288. this.name = name;
  289. return this;
  290. }
  291.  
  292. public void unsetName() {
  293. this.name = null;
  294. }
  295.  
  296. /** Returns true if field name is set (has been assigned a value) and false otherwise */
  297. public boolean isSetName() {
  298. return this.name != null;
  299. }
  300.  
  301. public void setNameIsSet(boolean value) {
  302. if (!value) {
  303. this.name = null;
  304. }
  305. }
  306.  
  307. public void setFieldValue(_Fields field, Object value) {
  308. switch (field) {
  309. case NAME:
  310. if (value == null) {
  311. unsetName();
  312. } else {
  313. setName((String)value);
  314. }
  315. break;
  316.  
  317. }
  318. }
  319.  
  320. public Object getFieldValue(_Fields field) {
  321. switch (field) {
  322. case NAME:
  323. return getName();
  324.  
  325. }
  326. throw new IllegalStateException();
  327. }
  328.  
  329. /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  330. public boolean isSet(_Fields field) {
  331. if (field == null) {
  332. throw new IllegalArgumentException();
  333. }
  334.  
  335. switch (field) {
  336. case NAME:
  337. return isSetName();
  338. }
  339. throw new IllegalStateException();
  340. }
  341.  
  342. @Override
  343. public boolean equals(Object that) {
  344. if (that == null)
  345. return false;
  346. if (that instanceof sayHi_args)
  347. return this.equals((sayHi_args)that);
  348. return false;
  349. }
  350.  
  351. public boolean equals(sayHi_args that) {
  352. if (that == null)
  353. return false;
  354.  
  355. boolean this_present_name = true && this.isSetName();
  356. boolean that_present_name = true && that.isSetName();
  357. if (this_present_name || that_present_name) {
  358. if (!(this_present_name && that_present_name))
  359. return false;
  360. if (!this.name.equals(that.name))
  361. return false;
  362. }
  363.  
  364. return true;
  365. }
  366.  
  367. @Override
  368. public int hashCode() {
  369. return 0;
  370. }
  371.  
  372. public int compareTo(sayHi_args other) {
  373. if (!getClass().equals(other.getClass())) {
  374. return getClass().getName().compareTo(other.getClass().getName());
  375. }
  376.  
  377. int lastComparison = 0;
  378. sayHi_args typedOther = (sayHi_args)other;
  379.  
  380. lastComparison = Boolean.valueOf(isSetName()).compareTo(typedOther.isSetName());
  381. if (lastComparison != 0) {
  382. return lastComparison;
  383. }
  384. if (isSetName()) {
  385. lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, typedOther.name);
  386. if (lastComparison != 0) {
  387. return lastComparison;
  388. }
  389. }
  390. return 0;
  391. }
  392.  
  393. public _Fields fieldForId(int fieldId) {
  394. return _Fields.findByThriftId(fieldId);
  395. }
  396.  
  397. public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
  398. schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  399. }
  400.  
  401. public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
  402. schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  403. }
  404.  
  405. @Override
  406. public String toString() {
  407. StringBuilder sb = new StringBuilder("sayHi_args(");
  408. boolean first = true;
  409.  
  410. sb.append("name:");
  411. if (this.name == null) {
  412. sb.append("null");
  413. } else {
  414. sb.append(this.name);
  415. }
  416. first = false;
  417. sb.append(")");
  418. return sb.toString();
  419. }
  420.  
  421. public void validate() throws org.apache.thrift.TException {
  422. // check for required fields
  423. }
  424.  
  425. private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
  426. try {
  427. write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
  428. } catch (org.apache.thrift.TException te) {
  429. throw new java.io.IOException(te);
  430. }
  431. }
  432.  
  433. private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
  434. try {
  435. read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
  436. } catch (org.apache.thrift.TException te) {
  437. throw new java.io.IOException(te);
  438. }
  439. }
  440.  
  441. private static class sayHi_argsStandardSchemeFactory implements SchemeFactory {
  442. public sayHi_argsStandardScheme getScheme() {
  443. return new sayHi_argsStandardScheme();
  444. }
  445. }
  446.  
  447. private static class sayHi_argsStandardScheme extends StandardScheme<sayHi_args> {
  448.  
  449. public void read(org.apache.thrift.protocol.TProtocol iprot, sayHi_args struct) throws org.apache.thrift.TException {
  450. org.apache.thrift.protocol.TField schemeField;
  451. iprot.readStructBegin();
  452. while (true)
  453. {
  454. schemeField = iprot.readFieldBegin();
  455. if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
  456. break;
  457. }
  458. switch (schemeField.id) {
  459. case 1: // NAME
  460. if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
  461. struct.name = iprot.readString();
  462. struct.setNameIsSet(true);
  463. } else {
  464. org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
  465. }
  466. break;
  467. default:
  468. org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
  469. }
  470. iprot.readFieldEnd();
  471. }
  472. iprot.readStructEnd();
  473.  
  474. // check for required fields of primitive type, which can't be checked in the validate method
  475. struct.validate();
  476. }
  477.  
  478. public void write(org.apache.thrift.protocol.TProtocol oprot, sayHi_args struct) throws org.apache.thrift.TException {
  479. struct.validate();
  480.  
  481. oprot.writeStructBegin(STRUCT_DESC);
  482. if (struct.name != null) {
  483. oprot.writeFieldBegin(NAME_FIELD_DESC);
  484. oprot.writeString(struct.name);
  485. oprot.writeFieldEnd();
  486. }
  487. oprot.writeFieldStop();
  488. oprot.writeStructEnd();
  489. }
  490.  
  491. }
  492.  
  493. private static class sayHi_argsTupleSchemeFactory implements SchemeFactory {
  494. public sayHi_argsTupleScheme getScheme() {
  495. return new sayHi_argsTupleScheme();
  496. }
  497. }
  498.  
  499. private static class sayHi_argsTupleScheme extends TupleScheme<sayHi_args> {
  500.  
  501. @Override
  502. public void write(org.apache.thrift.protocol.TProtocol prot, sayHi_args struct) throws org.apache.thrift.TException {
  503. TTupleProtocol oprot = (TTupleProtocol) prot;
  504. BitSet optionals = new BitSet();
  505. if (struct.isSetName()) {
  506. optionals.set(0);
  507. }
  508. oprot.writeBitSet(optionals, 1);
  509. if (struct.isSetName()) {
  510. oprot.writeString(struct.name);
  511. }
  512. }
  513.  
  514. @Override
  515. public void read(org.apache.thrift.protocol.TProtocol prot, sayHi_args struct) throws org.apache.thrift.TException {
  516. TTupleProtocol iprot = (TTupleProtocol) prot;
  517. BitSet incoming = iprot.readBitSet(1);
  518. if (incoming.get(0)) {
  519. struct.name = iprot.readString();
  520. struct.setNameIsSet(true);
  521. }
  522. }
  523. }
  524.  
  525. }
  526.  
  527. public static class sayHi_result implements org.apache.thrift.TBase<sayHi_result, sayHi_result._Fields>, java.io.Serializable, Cloneable {
  528. private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHi_result");
  529.  
  530. 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);
  531.  
  532. private static final Map<Class<?
  533.  
  534. extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  535. static {
  536. schemes.put(StandardScheme.class, new sayHi_resultStandardSchemeFactory());
  537. schemes.put(TupleScheme.class, new sayHi_resultTupleSchemeFactory());
  538. }
  539.  
  540. public String success; // required
  541.  
  542. /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  543. public enum _Fields implements org.apache.thrift.TFieldIdEnum {
  544. SUCCESS((short)0, "success");
  545.  
  546. private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
  547.  
  548. static {
  549. for (_Fields field : EnumSet.allOf(_Fields.class)) {
  550. byName.put(field.getFieldName(), field);
  551. }
  552. }
  553.  
  554. /**
  555. * Find the _Fields constant that matches fieldId, or null if its not found.
  556. */
  557. public static _Fields findByThriftId(int fieldId) {
  558. switch(fieldId) {
  559. case 0: // SUCCESS
  560. return SUCCESS;
  561. default:
  562. return null;
  563. }
  564. }
  565.  
  566. /**
  567. * Find the _Fields constant that matches fieldId, throwing an exception
  568. * if it is not found.
  569. */
  570. public static _Fields findByThriftIdOrThrow(int fieldId) {
  571. _Fields fields = findByThriftId(fieldId);
  572. if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
  573. return fields;
  574. }
  575.  
  576. /**
  577. * Find the _Fields constant that matches name, or null if its not found.
  578. */
  579. public static _Fields findByName(String name) {
  580. return byName.get(name);
  581. }
  582.  
  583. private final short _thriftId;
  584. private final String _fieldName;
  585.  
  586. _Fields(short thriftId, String fieldName) {
  587. _thriftId = thriftId;
  588. _fieldName = fieldName;
  589. }
  590.  
  591. public short getThriftFieldId() {
  592. return _thriftId;
  593. }
  594.  
  595. public String getFieldName() {
  596. return _fieldName;
  597. }
  598. }
  599.  
  600. // isset id assignments
  601. public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  602. static {
  603. Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
  604. tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
  605. new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
  606. metaDataMap = Collections.unmodifiableMap(tmpMap);
  607. org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHi_result.class, metaDataMap);
  608. }
  609.  
  610. public sayHi_result() {
  611. }
  612.  
  613. public sayHi_result(
  614. String success)
  615. {
  616. this();
  617. this.success = success;
  618. }
  619.  
  620. /**
  621. * Performs a deep copy on <i>other</i>.
  622. */
  623. public sayHi_result(sayHi_result other) {
  624. if (other.isSetSuccess()) {
  625. this.success = other.success;
  626. }
  627. }
  628.  
  629. public sayHi_result deepCopy() {
  630. return new sayHi_result(this);
  631. }
  632.  
  633. @Override
  634. public void clear() {
  635. this.success = null;
  636. }
  637.  
  638. public String getSuccess() {
  639. return this.success;
  640. }
  641.  
  642. public sayHi_result setSuccess(String success) {
  643. this.success = success;
  644. return this;
  645. }
  646.  
  647. public void unsetSuccess() {
  648. this.success = null;
  649. }
  650.  
  651. /** Returns true if field success is set (has been assigned a value) and false otherwise */
  652. public boolean isSetSuccess() {
  653. return this.success != null;
  654. }
  655.  
  656. public void setSuccessIsSet(boolean value) {
  657. if (!value) {
  658. this.success = null;
  659. }
  660. }
  661.  
  662. public void setFieldValue(_Fields field, Object value) {
  663. switch (field) {
  664. case SUCCESS:
  665. if (value == null) {
  666. unsetSuccess();
  667. } else {
  668. setSuccess((String)value);
  669. }
  670. break;
  671.  
  672. }
  673. }
  674.  
  675. public Object getFieldValue(_Fields field) {
  676. switch (field) {
  677. case SUCCESS:
  678. return getSuccess();
  679.  
  680. }
  681. throw new IllegalStateException();
  682. }
  683.  
  684. /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  685. public boolean isSet(_Fields field) {
  686. if (field == null) {
  687. throw new IllegalArgumentException();
  688. }
  689.  
  690. switch (field) {
  691. case SUCCESS:
  692. return isSetSuccess();
  693. }
  694. throw new IllegalStateException();
  695. }
  696.  
  697. @Override
  698. public boolean equals(Object that) {
  699. if (that == null)
  700. return false;
  701. if (that instanceof sayHi_result)
  702. return this.equals((sayHi_result)that);
  703. return false;
  704. }
  705.  
  706. public boolean equals(sayHi_result that) {
  707. if (that == null)
  708. return false;
  709.  
  710. boolean this_present_success = true && this.isSetSuccess();
  711. boolean that_present_success = true && that.isSetSuccess();
  712. if (this_present_success || that_present_success) {
  713. if (!(this_present_success && that_present_success))
  714. return false;
  715. if (!this.success.equals(that.success))
  716. return false;
  717. }
  718.  
  719. return true;
  720. }
  721.  
  722. @Override
  723. public int hashCode() {
  724. return 0;
  725. }
  726.  
  727. public int compareTo(sayHi_result other) {
  728. if (!getClass().equals(other.getClass())) {
  729. return getClass().getName().compareTo(other.getClass().getName());
  730. }
  731.  
  732. int lastComparison = 0;
  733. sayHi_result typedOther = (sayHi_result)other;
  734.  
  735. lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess());
  736. if (lastComparison != 0) {
  737. return lastComparison;
  738. }
  739. if (isSetSuccess()) {
  740. lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success);
  741. if (lastComparison != 0) {
  742. return lastComparison;
  743. }
  744. }
  745. return 0;
  746. }
  747.  
  748. public _Fields fieldForId(int fieldId) {
  749. return _Fields.findByThriftId(fieldId);
  750. }
  751.  
  752. public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
  753. schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  754. }
  755.  
  756. public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
  757. schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  758. }
  759.  
  760. @Override
  761. public String toString() {
  762. StringBuilder sb = new StringBuilder("sayHi_result(");
  763. boolean first = true;
  764.  
  765. sb.append("success:");
  766. if (this.success == null) {
  767. sb.append("null");
  768. } else {
  769. sb.append(this.success);
  770. }
  771. first = false;
  772. sb.append(")");
  773. return sb.toString();
  774. }
  775.  
  776. public void validate() throws org.apache.thrift.TException {
  777. // check for required fields
  778. }
  779.  
  780. private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
  781. try {
  782. write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
  783. } catch (org.apache.thrift.TException te) {
  784. throw new java.io.IOException(te);
  785. }
  786. }
  787.  
  788. private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
  789. try {
  790. read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
  791. } catch (org.apache.thrift.TException te) {
  792. throw new java.io.IOException(te);
  793. }
  794. }
  795.  
  796. private static class sayHi_resultStandardSchemeFactory implements SchemeFactory {
  797. public sayHi_resultStandardScheme getScheme() {
  798. return new sayHi_resultStandardScheme();
  799. }
  800. }
  801.  
  802. private static class sayHi_resultStandardScheme extends StandardScheme<sayHi_result> {
  803.  
  804. public void read(org.apache.thrift.protocol.TProtocol iprot, sayHi_result struct) throws org.apache.thrift.TException {
  805. org.apache.thrift.protocol.TField schemeField;
  806. iprot.readStructBegin();
  807. while (true)
  808. {
  809. schemeField = iprot.readFieldBegin();
  810. if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
  811. break;
  812. }
  813. switch (schemeField.id) {
  814. case 0: // SUCCESS
  815. if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
  816. struct.success = iprot.readString();
  817. struct.setSuccessIsSet(true);
  818. } else {
  819. org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
  820. }
  821. break;
  822. default:
  823. org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
  824. }
  825. iprot.readFieldEnd();
  826. }
  827. iprot.readStructEnd();
  828.  
  829. // check for required fields of primitive type, which can't be checked in the validate method
  830. struct.validate();
  831. }
  832.  
  833. public void write(org.apache.thrift.protocol.TProtocol oprot, sayHi_result struct) throws org.apache.thrift.TException {
  834. struct.validate();
  835.  
  836. oprot.writeStructBegin(STRUCT_DESC);
  837. if (struct.success != null) {
  838. oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
  839. oprot.writeString(struct.success);
  840. oprot.writeFieldEnd();
  841. }
  842. oprot.writeFieldStop();
  843. oprot.writeStructEnd();
  844. }
  845.  
  846. }
  847.  
  848. private static class sayHi_resultTupleSchemeFactory implements SchemeFactory {
  849. public sayHi_resultTupleScheme getScheme() {
  850. return new sayHi_resultTupleScheme();
  851. }
  852. }
  853.  
  854. private static class sayHi_resultTupleScheme extends TupleScheme<sayHi_result> {
  855.  
  856. @Override
  857. public void write(org.apache.thrift.protocol.TProtocol prot, sayHi_result struct) throws org.apache.thrift.TException {
  858. TTupleProtocol oprot = (TTupleProtocol) prot;
  859. BitSet optionals = new BitSet();
  860. if (struct.isSetSuccess()) {
  861. optionals.set(0);
  862. }
  863. oprot.writeBitSet(optionals, 1);
  864. if (struct.isSetSuccess()) {
  865. oprot.writeString(struct.success);
  866. }
  867. }
  868.  
  869. @Override
  870. public void read(org.apache.thrift.protocol.TProtocol prot, sayHi_result struct) throws org.apache.thrift.TException {
  871. TTupleProtocol iprot = (TTupleProtocol) prot;
  872. BitSet incoming = iprot.readBitSet(1);
  873. if (incoming.get(0)) {
  874. struct.success = iprot.readString();
  875. struct.setSuccessIsSet(true);
  876. }
  877. }
  878. }
  879.  
  880. }
  881.  
  882. }

4. 接口实现类

  1. package com.thrift.test;
  2.  
  3. import org.apache.thrift.TException;
  4.  
  5. public class DemoServiceImpl implements DemoService.Iface{
  6.  
  7. @Override
  8. public String sayHi(String name) throws TException {
  9. return "Hi " + name + ", from Thrift Server";
  10. }
  11.  
  12. }

5. client

  1. package com.thrift.test.client;
  2.  
  3. import org.apache.thrift.protocol.TCompactProtocol;
  4. import org.apache.thrift.protocol.TProtocol;
  5. import org.apache.thrift.transport.TFramedTransport;
  6. import org.apache.thrift.transport.TSocket;
  7. import org.apache.thrift.transport.TTransport;
  8.  
  9. import com.thrift.test.DemoService;
  10.  
  11. public class Client {
  12. public static void main(String[] args) throws Exception{
  13. TSocket socket = new TSocket("127.0.0.1", 9090);
  14. socket.setTimeout(3000);
  15. TTransport transport = new TFramedTransport(socket);
  16. TProtocol protocol = new TCompactProtocol(transport);
  17. transport.open();
  18. System.out.println("Connected to Thrfit Server");
  19.  
  20. DemoService.Client client = new DemoService.Client.Factory()
  21. .getClient(protocol);
  22. String result = client.sayHi("ITer_ZC");
  23. System.out.println(result);
  24. }
  25. }

6. server端

  1. package com.thrift.test.server;
  2.  
  3. import org.apache.thrift.TProcessor;
  4. import org.apache.thrift.protocol.TCompactProtocol;
  5. import org.apache.thrift.server.TNonblockingServer;
  6. import org.apache.thrift.server.TServer;
  7. import org.apache.thrift.transport.TNonblockingServerSocket;
  8.  
  9. import com.thrift.test.DemoService;
  10. import com.thrift.test.DemoService.Iface;
  11. import com.thrift.test.DemoServiceImpl;
  12.  
  13. public class Server {
  14.     public static void main(String[] args){
  15.         TNonblockingServerSocket socket;
  16.         try {
  17.             socket = new TNonblockingServerSocket(9090);
  18.             TNonblockingServer.Args options = new TNonblockingServer.Args(socket);
  19.             TProcessor processor = new DemoService.Processor<Iface>(new DemoServiceImpl());
  20.             options.processor(processor);
  21.             options.protocolFactory(new TCompactProtocol.Factory());
  22.             TServer server = new TNonblockingServer(options);
  23.             System.out.println("Thrift Server is running at 9090 port");
  24.             server.serve();        
  25.         } catch (Exception e) {
  26.             throw new RuntimeException(e);
  27.         }
  28.     }
  29. }

7. server端执行截图

8. client执行截图

9. 依赖的jar包

Thrift源代码分析(八)--总结加一个完整的可执行的Thrift样例的更多相关文章

  1. RTMPdump(libRTMP) 源代码分析 6: 建立一个流媒体连接 (NetStream部分 1)

    ===================================================== RTMPdump(libRTMP) 源代码分析系列文章: RTMPdump 源代码分析 1: ...

  2. RTMPdump(libRTMP) 源代码分析 7: 建立一个流媒体连接 (NetStream部分 2)

    ===================================================== RTMPdump(libRTMP) 源代码分析系列文章: RTMPdump 源代码分析 1: ...

  3. RTMPdump(libRTMP) 源代码分析 5: 建立一个流媒体连接 (NetConnection部分)

    ===================================================== RTMPdump(libRTMP) 源代码分析系列文章: RTMPdump 源代码分析 1: ...

  4. LIRe 源代码分析 4:建立索引(DocumentBuilder)[以颜色布局为例]

    ===================================================== LIRe源代码分析系列文章列表: LIRe 源代码分析 1:整体结构 LIRe 源代码分析 ...

  5. Dubbo 源代码分析八:再说 Provider 线程池被 EXHAUSTED

    转自:http://manzhizhen.iteye.com/blog/2391177 在上回<Dubbo源代码实现六>中我们已经了解到,对于Dubbo集群中的Provider角色,有IO ...

  6. rnnlm源代码分析(八)

    系列前言 參考文献: RNNLM - Recurrent Neural Network  Language Modeling Toolkit(点此阅读) Recurrent neural networ ...

  7. Thrift源代码分析(七)-- TServerserver分析

    Thrift採用了TServer来作为server的抽象,提供了多种类型的server实现.用TServerTransport作为server的Acceptor抽象,来监听端口.创建clientSoc ...

  8. 我的第一个chrome扩展(1)——读样例,实现时钟

    学习chrome扩展开发: 与网页类似,需要的知识:html,javascript chrome扩展程序的构成: manifest.json:对扩展程序的整体描述文件 { "manifest ...

  9. 一个平时写程序通用的Makefile样例

    //需要目标名和程序名字相同 .PHONY:clean all //伪目标 CC=gcc CFLAGS=-Wall -g BIN= //目标 all:$(BIN) %.o:%.c $(CC) $(CF ...

随机推荐

  1. 【洛谷4158/BZOJ1296】[SCOI2009]粉刷匠(动态规划)

    题目:洛谷4158 分析: 这题一看就是动态规划. 可以看出,如果每个木条粉刷的次数是固定的,那么这些木条是互不干扰的,因此对于每个木条可以通过dp来求出把T次中的j次分配给这个木条时可以获得的最大正 ...

  2. ACM_招新笔试题系列——买包子

    招新笔试题系列——买包子 Time Limit: 2000/1000ms (Java/Others) Problem Description: 小华刚到大学,一天早上她替她室友买早餐,一共要N个包子. ...

  3. 学习c语言的感想

    其实个人认为无论学习什么语言,最重要的是掌握习编程思想,然而C语言一种学习编程思想的基础语言.所以,C语言的重要性不言而喻. 一.课本 无论用的是什么书,要学好C语言,把书上的每一个例题.习题的代码读 ...

  4. 15年用canvas画的

    请恕我当年的工作太轻松,用canvas手打了一个图,技术含量并没有什么,现在看看,甚是怀念_(¦3」∠)_ <!DOCTYPE html> <html> <head&g ...

  5. no斜体 背景图片坐标

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. SAS进阶《深入解析SAS》之SAS数据挖掘的一般流程

    SAS进阶<深入解析SAS>之SAS数据挖掘的一般流程 1. 所谓数据挖掘,是指通过对大量的数据进行选择.探索与建模,来揭示包含在数据中以前不为人所知的模式或规律,从而为商业活动或科学研究 ...

  7. PHP魔术法__set和__get

    __set: 在给不可访问属性赋值时,__set() 会被调用.语法如下: public void __set ( string $name , mixed $value ) __get: 读取不可访 ...

  8. Spring处理自动装配的歧义性

    1.标识首选的bean 2.使用限定符@Qualifier 首先在bean的声明上添加@Qualifier 注解: @Component @Qualifier("cdtest") ...

  9. SolidWorks学习笔记(一)

    一.草图绘制 1.简单命令 先直线后圆弧,几何约束.尺寸标定 2.圆周阵列 3.几何关系——对称 添加几何约束:圆弧相等.关于竖直中心线的对称 4.捕捉圆心 5.尺寸锁定,有圆弧的,先直后圆 6. 7 ...

  10. vue-cli3 中的环境变量

    官方文档是这样写的: src同名文件夹下的建立 .env.[model] 配置文件  // mode:production development ... 载入的变量会对vue-cli-service ...