Thrift源代码分析(八)--总结加一个完整的可执行的Thrift样例
前面七篇文章分析了Thrfit的方方面面,看到这里时应该对Thrift有了深入的理解。
Thrift源代码分析(五)-- FrameBuffer类分析
Thrift源代码分析(六)-- Transport传输层分析
Thrift源代码分析(七)-- TServerserver分析
以下通过一个实际能够执行的样例来跑一跑Thrift,结束这个主题
1. 通过IDL来定义接口: DemoService.thrift
- namespace java com.thrift.test
- service DemoService{
- string sayHi(1:string name);
- }
2. 依据IDL自己主动生成代码
- thrift -r --gen java DemoService.thrift
3. 生成的代码供server和client调用
- /**
- * Autogenerated by Thrift Compiler (0.8.0)
- *
- * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
- * @generated
- */
- package com.thrift.test;
- import org.apache.thrift.scheme.IScheme;
- import org.apache.thrift.scheme.SchemeFactory;
- import org.apache.thrift.scheme.StandardScheme;
- import org.apache.thrift.scheme.TupleScheme;
- import org.apache.thrift.protocol.TTupleProtocol;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Map;
- import java.util.HashMap;
- import java.util.EnumMap;
- import java.util.Set;
- import java.util.HashSet;
- import java.util.EnumSet;
- import java.util.Collections;
- import java.util.BitSet;
- import java.nio.ByteBuffer;
- import java.util.Arrays;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class DemoService {
- public interface Iface {
- public String sayHi(String name) throws org.apache.thrift.TException;
- }
- public interface AsyncIface {
- public void sayHi(String name, org.apache.thrift.async.AsyncMethodCallback<AsyncClient.sayHi_call> resultHandler) throws org.apache.thrift.TException;
- }
- public static class Client extends org.apache.thrift.TServiceClient implements Iface {
- public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
- public Factory() {}
- public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
- return new Client(prot);
- }
- public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
- return new Client(iprot, oprot);
- }
- }
- public Client(org.apache.thrift.protocol.TProtocol prot)
- {
- super(prot, prot);
- }
- public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
- super(iprot, oprot);
- }
- public String sayHi(String name) throws org.apache.thrift.TException
- {
- send_sayHi(name);
- return recv_sayHi();
- }
- public void send_sayHi(String name) throws org.apache.thrift.TException
- {
- sayHi_args args = new sayHi_args();
- args.setName(name);
- sendBase("sayHi", args);
- }
- public String recv_sayHi() throws org.apache.thrift.TException
- {
- sayHi_result result = new sayHi_result();
- receiveBase(result, "sayHi");
- if (result.isSetSuccess()) {
- return result.success;
- }
- throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHi failed: unknown result");
- }
- }
- public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
- public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
- private org.apache.thrift.async.TAsyncClientManager clientManager;
- private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
- public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
- this.clientManager = clientManager;
- this.protocolFactory = protocolFactory;
- }
- public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
- return new AsyncClient(protocolFactory, clientManager, transport);
- }
- }
- public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
- super(protocolFactory, clientManager, transport);
- }
- public void sayHi(String name, org.apache.thrift.async.AsyncMethodCallback<sayHi_call> resultHandler) throws org.apache.thrift.TException {
- checkReady();
- sayHi_call method_call = new sayHi_call(name, resultHandler, this, ___protocolFactory, ___transport);
- this.___currentMethod = method_call;
- ___manager.call(method_call);
- }
- public static class sayHi_call extends org.apache.thrift.async.TAsyncMethodCall {
- private String name;
- 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 {
- super(client, protocolFactory, transport, resultHandler, false);
- this.name = name;
- }
- public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
- prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sayHi", org.apache.thrift.protocol.TMessageType.CALL, 0));
- sayHi_args args = new sayHi_args();
- args.setName(name);
- args.write(prot);
- prot.writeMessageEnd();
- }
- public String getResult() throws org.apache.thrift.TException {
- if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
- throw new IllegalStateException("Method call not finished!");
- }
- org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
- org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
- return (new Client(prot)).recv_sayHi();
- }
- }
- }
- public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
- private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());
- public Processor(I iface) {
- super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
- }
- protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
- super(iface, getProcessMap(processMap));
- }
- 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) {
- processMap.put("sayHi", new sayHi());
- return processMap;
- }
- private static class sayHi<I extends Iface> extends org.apache.thrift.ProcessFunction<I, sayHi_args> {
- public sayHi() {
- super("sayHi");
- }
- protected sayHi_args getEmptyArgsInstance() {
- return new sayHi_args();
- }
- protected sayHi_result getResult(I iface, sayHi_args args) throws org.apache.thrift.TException {
- sayHi_result result = new sayHi_result();
- result.success = iface.sayHi(args.name);
- return result;
- }
- }
- }
- public static class sayHi_args implements org.apache.thrift.TBase<sayHi_args, sayHi_args._Fields>, java.io.Serializable, Cloneable {
- private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHi_args");
- 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);
- private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
- static {
- schemes.put(StandardScheme.class, new sayHi_argsStandardSchemeFactory());
- schemes.put(TupleScheme.class, new sayHi_argsTupleSchemeFactory());
- }
- public String name; // required
- /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
- public enum _Fields implements org.apache.thrift.TFieldIdEnum {
- NAME((short)1, "name");
- private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
- static {
- for (_Fields field : EnumSet.allOf(_Fields.class)) {
- byName.put(field.getFieldName(), field);
- }
- }
- /**
- * Find the _Fields constant that matches fieldId, or null if its not found.
- */
- public static _Fields findByThriftId(int fieldId) {
- switch(fieldId) {
- case 1: // NAME
- return NAME;
- default:
- return null;
- }
- }
- /**
- * Find the _Fields constant that matches fieldId, throwing an exception
- * if it is not found.
- */
- public static _Fields findByThriftIdOrThrow(int fieldId) {
- _Fields fields = findByThriftId(fieldId);
- if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
- return fields;
- }
- /**
- * Find the _Fields constant that matches name, or null if its not found.
- */
- public static _Fields findByName(String name) {
- return byName.get(name);
- }
- private final short _thriftId;
- private final String _fieldName;
- _Fields(short thriftId, String fieldName) {
- _thriftId = thriftId;
- _fieldName = fieldName;
- }
- public short getThriftFieldId() {
- return _thriftId;
- }
- public String getFieldName() {
- return _fieldName;
- }
- }
- // isset id assignments
- public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
- static {
- Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
- tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT,
- new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
- metaDataMap = Collections.unmodifiableMap(tmpMap);
- org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHi_args.class, metaDataMap);
- }
- public sayHi_args() {
- }
- public sayHi_args(
- String name)
- {
- this();
- this.name = name;
- }
- /**
- * Performs a deep copy on <i>other</i>.
- */
- public sayHi_args(sayHi_args other) {
- if (other.isSetName()) {
- this.name = other.name;
- }
- }
- public sayHi_args deepCopy() {
- return new sayHi_args(this);
- }
- @Override
- public void clear() {
- this.name = null;
- }
- public String getName() {
- return this.name;
- }
- public sayHi_args setName(String name) {
- this.name = name;
- return this;
- }
- public void unsetName() {
- this.name = null;
- }
- /** Returns true if field name is set (has been assigned a value) and false otherwise */
- public boolean isSetName() {
- return this.name != null;
- }
- public void setNameIsSet(boolean value) {
- if (!value) {
- this.name = null;
- }
- }
- public void setFieldValue(_Fields field, Object value) {
- switch (field) {
- case NAME:
- if (value == null) {
- unsetName();
- } else {
- setName((String)value);
- }
- break;
- }
- }
- public Object getFieldValue(_Fields field) {
- switch (field) {
- case NAME:
- return getName();
- }
- throw new IllegalStateException();
- }
- /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
- public boolean isSet(_Fields field) {
- if (field == null) {
- throw new IllegalArgumentException();
- }
- switch (field) {
- case NAME:
- return isSetName();
- }
- throw new IllegalStateException();
- }
- @Override
- public boolean equals(Object that) {
- if (that == null)
- return false;
- if (that instanceof sayHi_args)
- return this.equals((sayHi_args)that);
- return false;
- }
- public boolean equals(sayHi_args that) {
- if (that == null)
- return false;
- boolean this_present_name = true && this.isSetName();
- boolean that_present_name = true && that.isSetName();
- if (this_present_name || that_present_name) {
- if (!(this_present_name && that_present_name))
- return false;
- if (!this.name.equals(that.name))
- return false;
- }
- return true;
- }
- @Override
- public int hashCode() {
- return 0;
- }
- public int compareTo(sayHi_args other) {
- if (!getClass().equals(other.getClass())) {
- return getClass().getName().compareTo(other.getClass().getName());
- }
- int lastComparison = 0;
- sayHi_args typedOther = (sayHi_args)other;
- lastComparison = Boolean.valueOf(isSetName()).compareTo(typedOther.isSetName());
- if (lastComparison != 0) {
- return lastComparison;
- }
- if (isSetName()) {
- lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, typedOther.name);
- if (lastComparison != 0) {
- return lastComparison;
- }
- }
- return 0;
- }
- public _Fields fieldForId(int fieldId) {
- return _Fields.findByThriftId(fieldId);
- }
- public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
- schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
- }
- public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
- schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("sayHi_args(");
- boolean first = true;
- sb.append("name:");
- if (this.name == null) {
- sb.append("null");
- } else {
- sb.append(this.name);
- }
- first = false;
- sb.append(")");
- return sb.toString();
- }
- public void validate() throws org.apache.thrift.TException {
- // check for required fields
- }
- private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
- try {
- write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
- } catch (org.apache.thrift.TException te) {
- throw new java.io.IOException(te);
- }
- }
- private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
- try {
- read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
- } catch (org.apache.thrift.TException te) {
- throw new java.io.IOException(te);
- }
- }
- private static class sayHi_argsStandardSchemeFactory implements SchemeFactory {
- public sayHi_argsStandardScheme getScheme() {
- return new sayHi_argsStandardScheme();
- }
- }
- private static class sayHi_argsStandardScheme extends StandardScheme<sayHi_args> {
- public void read(org.apache.thrift.protocol.TProtocol iprot, sayHi_args struct) throws org.apache.thrift.TException {
- org.apache.thrift.protocol.TField schemeField;
- iprot.readStructBegin();
- while (true)
- {
- schemeField = iprot.readFieldBegin();
- if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
- break;
- }
- switch (schemeField.id) {
- case 1: // NAME
- if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
- struct.name = iprot.readString();
- struct.setNameIsSet(true);
- } else {
- org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
- }
- break;
- default:
- org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
- }
- iprot.readFieldEnd();
- }
- iprot.readStructEnd();
- // check for required fields of primitive type, which can't be checked in the validate method
- struct.validate();
- }
- public void write(org.apache.thrift.protocol.TProtocol oprot, sayHi_args struct) throws org.apache.thrift.TException {
- struct.validate();
- oprot.writeStructBegin(STRUCT_DESC);
- if (struct.name != null) {
- oprot.writeFieldBegin(NAME_FIELD_DESC);
- oprot.writeString(struct.name);
- oprot.writeFieldEnd();
- }
- oprot.writeFieldStop();
- oprot.writeStructEnd();
- }
- }
- private static class sayHi_argsTupleSchemeFactory implements SchemeFactory {
- public sayHi_argsTupleScheme getScheme() {
- return new sayHi_argsTupleScheme();
- }
- }
- private static class sayHi_argsTupleScheme extends TupleScheme<sayHi_args> {
- @Override
- public void write(org.apache.thrift.protocol.TProtocol prot, sayHi_args struct) throws org.apache.thrift.TException {
- TTupleProtocol oprot = (TTupleProtocol) prot;
- BitSet optionals = new BitSet();
- if (struct.isSetName()) {
- optionals.set(0);
- }
- oprot.writeBitSet(optionals, 1);
- if (struct.isSetName()) {
- oprot.writeString(struct.name);
- }
- }
- @Override
- public void read(org.apache.thrift.protocol.TProtocol prot, sayHi_args struct) throws org.apache.thrift.TException {
- TTupleProtocol iprot = (TTupleProtocol) prot;
- BitSet incoming = iprot.readBitSet(1);
- if (incoming.get(0)) {
- struct.name = iprot.readString();
- struct.setNameIsSet(true);
- }
- }
- }
- }
- public static class sayHi_result implements org.apache.thrift.TBase<sayHi_result, sayHi_result._Fields>, java.io.Serializable, Cloneable {
- private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHi_result");
- 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);
- private static final Map<Class<?
- extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
- static {
- schemes.put(StandardScheme.class, new sayHi_resultStandardSchemeFactory());
- schemes.put(TupleScheme.class, new sayHi_resultTupleSchemeFactory());
- }
- public String success; // required
- /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
- public enum _Fields implements org.apache.thrift.TFieldIdEnum {
- SUCCESS((short)0, "success");
- private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
- static {
- for (_Fields field : EnumSet.allOf(_Fields.class)) {
- byName.put(field.getFieldName(), field);
- }
- }
- /**
- * Find the _Fields constant that matches fieldId, or null if its not found.
- */
- public static _Fields findByThriftId(int fieldId) {
- switch(fieldId) {
- case 0: // SUCCESS
- return SUCCESS;
- default:
- return null;
- }
- }
- /**
- * Find the _Fields constant that matches fieldId, throwing an exception
- * if it is not found.
- */
- public static _Fields findByThriftIdOrThrow(int fieldId) {
- _Fields fields = findByThriftId(fieldId);
- if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
- return fields;
- }
- /**
- * Find the _Fields constant that matches name, or null if its not found.
- */
- public static _Fields findByName(String name) {
- return byName.get(name);
- }
- private final short _thriftId;
- private final String _fieldName;
- _Fields(short thriftId, String fieldName) {
- _thriftId = thriftId;
- _fieldName = fieldName;
- }
- public short getThriftFieldId() {
- return _thriftId;
- }
- public String getFieldName() {
- return _fieldName;
- }
- }
- // isset id assignments
- public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
- static {
- Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
- tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
- new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
- metaDataMap = Collections.unmodifiableMap(tmpMap);
- org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHi_result.class, metaDataMap);
- }
- public sayHi_result() {
- }
- public sayHi_result(
- String success)
- {
- this();
- this.success = success;
- }
- /**
- * Performs a deep copy on <i>other</i>.
- */
- public sayHi_result(sayHi_result other) {
- if (other.isSetSuccess()) {
- this.success = other.success;
- }
- }
- public sayHi_result deepCopy() {
- return new sayHi_result(this);
- }
- @Override
- public void clear() {
- this.success = null;
- }
- public String getSuccess() {
- return this.success;
- }
- public sayHi_result setSuccess(String success) {
- this.success = success;
- return this;
- }
- public void unsetSuccess() {
- this.success = null;
- }
- /** Returns true if field success is set (has been assigned a value) and false otherwise */
- public boolean isSetSuccess() {
- return this.success != null;
- }
- public void setSuccessIsSet(boolean value) {
- if (!value) {
- this.success = null;
- }
- }
- public void setFieldValue(_Fields field, Object value) {
- switch (field) {
- case SUCCESS:
- if (value == null) {
- unsetSuccess();
- } else {
- setSuccess((String)value);
- }
- break;
- }
- }
- public Object getFieldValue(_Fields field) {
- switch (field) {
- case SUCCESS:
- return getSuccess();
- }
- throw new IllegalStateException();
- }
- /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
- public boolean isSet(_Fields field) {
- if (field == null) {
- throw new IllegalArgumentException();
- }
- switch (field) {
- case SUCCESS:
- return isSetSuccess();
- }
- throw new IllegalStateException();
- }
- @Override
- public boolean equals(Object that) {
- if (that == null)
- return false;
- if (that instanceof sayHi_result)
- return this.equals((sayHi_result)that);
- return false;
- }
- public boolean equals(sayHi_result that) {
- if (that == null)
- return false;
- boolean this_present_success = true && this.isSetSuccess();
- boolean that_present_success = true && that.isSetSuccess();
- if (this_present_success || that_present_success) {
- if (!(this_present_success && that_present_success))
- return false;
- if (!this.success.equals(that.success))
- return false;
- }
- return true;
- }
- @Override
- public int hashCode() {
- return 0;
- }
- public int compareTo(sayHi_result other) {
- if (!getClass().equals(other.getClass())) {
- return getClass().getName().compareTo(other.getClass().getName());
- }
- int lastComparison = 0;
- sayHi_result typedOther = (sayHi_result)other;
- lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess());
- if (lastComparison != 0) {
- return lastComparison;
- }
- if (isSetSuccess()) {
- lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success);
- if (lastComparison != 0) {
- return lastComparison;
- }
- }
- return 0;
- }
- public _Fields fieldForId(int fieldId) {
- return _Fields.findByThriftId(fieldId);
- }
- public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
- schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
- }
- public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
- schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("sayHi_result(");
- boolean first = true;
- sb.append("success:");
- if (this.success == null) {
- sb.append("null");
- } else {
- sb.append(this.success);
- }
- first = false;
- sb.append(")");
- return sb.toString();
- }
- public void validate() throws org.apache.thrift.TException {
- // check for required fields
- }
- private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
- try {
- write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
- } catch (org.apache.thrift.TException te) {
- throw new java.io.IOException(te);
- }
- }
- private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
- try {
- read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
- } catch (org.apache.thrift.TException te) {
- throw new java.io.IOException(te);
- }
- }
- private static class sayHi_resultStandardSchemeFactory implements SchemeFactory {
- public sayHi_resultStandardScheme getScheme() {
- return new sayHi_resultStandardScheme();
- }
- }
- private static class sayHi_resultStandardScheme extends StandardScheme<sayHi_result> {
- public void read(org.apache.thrift.protocol.TProtocol iprot, sayHi_result struct) throws org.apache.thrift.TException {
- org.apache.thrift.protocol.TField schemeField;
- iprot.readStructBegin();
- while (true)
- {
- schemeField = iprot.readFieldBegin();
- if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
- break;
- }
- switch (schemeField.id) {
- case 0: // SUCCESS
- if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
- struct.success = iprot.readString();
- struct.setSuccessIsSet(true);
- } else {
- org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
- }
- break;
- default:
- org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
- }
- iprot.readFieldEnd();
- }
- iprot.readStructEnd();
- // check for required fields of primitive type, which can't be checked in the validate method
- struct.validate();
- }
- public void write(org.apache.thrift.protocol.TProtocol oprot, sayHi_result struct) throws org.apache.thrift.TException {
- struct.validate();
- oprot.writeStructBegin(STRUCT_DESC);
- if (struct.success != null) {
- oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
- oprot.writeString(struct.success);
- oprot.writeFieldEnd();
- }
- oprot.writeFieldStop();
- oprot.writeStructEnd();
- }
- }
- private static class sayHi_resultTupleSchemeFactory implements SchemeFactory {
- public sayHi_resultTupleScheme getScheme() {
- return new sayHi_resultTupleScheme();
- }
- }
- private static class sayHi_resultTupleScheme extends TupleScheme<sayHi_result> {
- @Override
- public void write(org.apache.thrift.protocol.TProtocol prot, sayHi_result struct) throws org.apache.thrift.TException {
- TTupleProtocol oprot = (TTupleProtocol) prot;
- BitSet optionals = new BitSet();
- if (struct.isSetSuccess()) {
- optionals.set(0);
- }
- oprot.writeBitSet(optionals, 1);
- if (struct.isSetSuccess()) {
- oprot.writeString(struct.success);
- }
- }
- @Override
- public void read(org.apache.thrift.protocol.TProtocol prot, sayHi_result struct) throws org.apache.thrift.TException {
- TTupleProtocol iprot = (TTupleProtocol) prot;
- BitSet incoming = iprot.readBitSet(1);
- if (incoming.get(0)) {
- struct.success = iprot.readString();
- struct.setSuccessIsSet(true);
- }
- }
- }
- }
- }
4. 接口实现类
- package com.thrift.test;
- import org.apache.thrift.TException;
- public class DemoServiceImpl implements DemoService.Iface{
- @Override
- public String sayHi(String name) throws TException {
- return "Hi " + name + ", from Thrift Server";
- }
- }
5. client
- package com.thrift.test.client;
- import org.apache.thrift.protocol.TCompactProtocol;
- import org.apache.thrift.protocol.TProtocol;
- import org.apache.thrift.transport.TFramedTransport;
- import org.apache.thrift.transport.TSocket;
- import org.apache.thrift.transport.TTransport;
- import com.thrift.test.DemoService;
- public class Client {
- public static void main(String[] args) throws Exception{
- TSocket socket = new TSocket("127.0.0.1", 9090);
- socket.setTimeout(3000);
- TTransport transport = new TFramedTransport(socket);
- TProtocol protocol = new TCompactProtocol(transport);
- transport.open();
- System.out.println("Connected to Thrfit Server");
- DemoService.Client client = new DemoService.Client.Factory()
- .getClient(protocol);
- String result = client.sayHi("ITer_ZC");
- System.out.println(result);
- }
- }
6. server端
- package com.thrift.test.server;
- import org.apache.thrift.TProcessor;
- import org.apache.thrift.protocol.TCompactProtocol;
- import org.apache.thrift.server.TNonblockingServer;
- import org.apache.thrift.server.TServer;
- import org.apache.thrift.transport.TNonblockingServerSocket;
- import com.thrift.test.DemoService;
- import com.thrift.test.DemoService.Iface;
- import com.thrift.test.DemoServiceImpl;
- public class Server {
- public static void main(String[] args){
- TNonblockingServerSocket socket;
- try {
- socket = new TNonblockingServerSocket(9090);
- TNonblockingServer.Args options = new TNonblockingServer.Args(socket);
- TProcessor processor = new DemoService.Processor<Iface>(new DemoServiceImpl());
- options.processor(processor);
- options.protocolFactory(new TCompactProtocol.Factory());
- TServer server = new TNonblockingServer(options);
- System.out.println("Thrift Server is running at 9090 port");
- server.serve();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
7. server端执行截图
8. client执行截图
9. 依赖的jar包
Thrift源代码分析(八)--总结加一个完整的可执行的Thrift样例的更多相关文章
- RTMPdump(libRTMP) 源代码分析 6: 建立一个流媒体连接 (NetStream部分 1)
===================================================== RTMPdump(libRTMP) 源代码分析系列文章: RTMPdump 源代码分析 1: ...
- RTMPdump(libRTMP) 源代码分析 7: 建立一个流媒体连接 (NetStream部分 2)
===================================================== RTMPdump(libRTMP) 源代码分析系列文章: RTMPdump 源代码分析 1: ...
- RTMPdump(libRTMP) 源代码分析 5: 建立一个流媒体连接 (NetConnection部分)
===================================================== RTMPdump(libRTMP) 源代码分析系列文章: RTMPdump 源代码分析 1: ...
- LIRe 源代码分析 4:建立索引(DocumentBuilder)[以颜色布局为例]
===================================================== LIRe源代码分析系列文章列表: LIRe 源代码分析 1:整体结构 LIRe 源代码分析 ...
- Dubbo 源代码分析八:再说 Provider 线程池被 EXHAUSTED
转自:http://manzhizhen.iteye.com/blog/2391177 在上回<Dubbo源代码实现六>中我们已经了解到,对于Dubbo集群中的Provider角色,有IO ...
- rnnlm源代码分析(八)
系列前言 參考文献: RNNLM - Recurrent Neural Network Language Modeling Toolkit(点此阅读) Recurrent neural networ ...
- Thrift源代码分析(七)-- TServerserver分析
Thrift採用了TServer来作为server的抽象,提供了多种类型的server实现.用TServerTransport作为server的Acceptor抽象,来监听端口.创建clientSoc ...
- 我的第一个chrome扩展(1)——读样例,实现时钟
学习chrome扩展开发: 与网页类似,需要的知识:html,javascript chrome扩展程序的构成: manifest.json:对扩展程序的整体描述文件 { "manifest ...
- 一个平时写程序通用的Makefile样例
//需要目标名和程序名字相同 .PHONY:clean all //伪目标 CC=gcc CFLAGS=-Wall -g BIN= //目标 all:$(BIN) %.o:%.c $(CC) $(CF ...
随机推荐
- 【洛谷4158/BZOJ1296】[SCOI2009]粉刷匠(动态规划)
题目:洛谷4158 分析: 这题一看就是动态规划. 可以看出,如果每个木条粉刷的次数是固定的,那么这些木条是互不干扰的,因此对于每个木条可以通过dp来求出把T次中的j次分配给这个木条时可以获得的最大正 ...
- ACM_招新笔试题系列——买包子
招新笔试题系列——买包子 Time Limit: 2000/1000ms (Java/Others) Problem Description: 小华刚到大学,一天早上她替她室友买早餐,一共要N个包子. ...
- 学习c语言的感想
其实个人认为无论学习什么语言,最重要的是掌握习编程思想,然而C语言一种学习编程思想的基础语言.所以,C语言的重要性不言而喻. 一.课本 无论用的是什么书,要学好C语言,把书上的每一个例题.习题的代码读 ...
- 15年用canvas画的
请恕我当年的工作太轻松,用canvas手打了一个图,技术含量并没有什么,现在看看,甚是怀念_(¦3」∠)_ <!DOCTYPE html> <html> <head&g ...
- no斜体 背景图片坐标
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- SAS进阶《深入解析SAS》之SAS数据挖掘的一般流程
SAS进阶<深入解析SAS>之SAS数据挖掘的一般流程 1. 所谓数据挖掘,是指通过对大量的数据进行选择.探索与建模,来揭示包含在数据中以前不为人所知的模式或规律,从而为商业活动或科学研究 ...
- PHP魔术法__set和__get
__set: 在给不可访问属性赋值时,__set() 会被调用.语法如下: public void __set ( string $name , mixed $value ) __get: 读取不可访 ...
- Spring处理自动装配的歧义性
1.标识首选的bean 2.使用限定符@Qualifier 首先在bean的声明上添加@Qualifier 注解: @Component @Qualifier("cdtest") ...
- SolidWorks学习笔记(一)
一.草图绘制 1.简单命令 先直线后圆弧,几何约束.尺寸标定 2.圆周阵列 3.几何关系——对称 添加几何约束:圆弧相等.关于竖直中心线的对称 4.捕捉圆心 5.尺寸锁定,有圆弧的,先直后圆 6. 7 ...
- vue-cli3 中的环境变量
官方文档是这样写的: src同名文件夹下的建立 .env.[model] 配置文件 // mode:production development ... 载入的变量会对vue-cli-service ...