Thrift 入门之helloWorld

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thrift 入门之helloWorld相关的知识,希望对你有一定的参考价值。

不多说,先看项目结构

首先先编写一个hello.thrift的文件

hello.thrift

namespace java sawshaw

service HelloService {
     string hello(1:string method, 2:string param)
}

 注意了,这个namespace是 thrift 根目录下tutorial目录的gen-java目录下的,如果没有这个目录,先cmd到tutorial目录,执行thrift -r --gen java tutorial.thrift。就会看到一个gen-java目录了,而这个sawshaw是我自定义的目录,把这个hello.thrift文件放到和tutorial目录同级,cmd到该目录后执行thrift -r --gen java hello.thrift

可以看到生成了一个HelloService的java类

把这个类复制到项目下面改下包名就可以了

再写个实现类HelloImpl对客户端的请求作响应

HelloImpl

package com.sawshaw.thrift;

import org.apache.thrift.TException;

import com.sawshaw.thrift.HelloService.Iface;

public class HelloImpl implements Iface{

	public String hello(String method, String param) throws TException {
		return "method:"+method+",param:"+param;
	}

}

编写服务端代码以启动server

HelloServer

package com.sawshaw.thrift;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;

import com.sawshaw.thrift.HelloService.Iface;

public class HelloServer {
	public static void main(String[] args) throws TTransportException {
        HelloService.Iface impl=new HelloImpl();
        HelloService.Processor<Iface> processor =   
        		new HelloService.Processor<Iface>(impl);
        TServerTransport serverTransport = new TServerSocket(8080);  
        TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(serverTransport);  
        System.out.println("server has start...");
        tArgs.processor(processor);  
        tArgs.protocolFactory(new TBinaryProtocol.Factory());  
        TServer server = new TThreadPoolServer(tArgs);  
        server.serve();  
	}
}  

编写客户端HelloClient调用服务端代码

HelloClient

package com.sawshaw.thrift;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

public class HelloClient {
	public static void main(String[] args) {
		TTransport transport;
		transport = new TSocket("localhost", 8080);
        try {
			transport.open();
		} catch (TTransportException e1) {
			e1.printStackTrace();
		}
        TProtocol protocol = new TBinaryProtocol(transport);
        HelloService.Iface client = new HelloService.Client(protocol);
        // 调用服务的 hello 方法
        String resp = null;
		try {
			resp = client.hello("method","param");
		} catch (TException e) {
			e.printStackTrace();
		}
        System.out.println("resp:"+resp);
        transport.close();
	}

}

 当然pom.xml要引用thrift的包,会自动加载thrift的依赖包

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sawshaw</groupId>
  <artifactId>thrift</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>thrift</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
  <groupId>org.apache.thrift</groupId>
  <artifactId>libthrift</artifactId>
  <version>0.11.0</version>
</dependency>
  </dependencies>
</project> 

服务端启动后,客户端运行结果:

resp:method:method,param:param  

 补上HelloService,在eclipse OXYGEN版本里面竟然报错了,这个就一点恶心了,另外OXYGEN版本的可以装activiti插件,Neon.3 Release (4.6.3)这个版本又装不了这个插件,还有更恶心的事情吗。。。

/**
 * Autogenerated by Thrift Compiler (0.11.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.sawshaw.thrift;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.11.0)", date = "2018-03-27")
public class HelloService {

  public interface Iface {

    public java.lang.String hello(java.lang.String method, java.lang.String param) throws org.apache.thrift.TException;

  }

  public interface AsyncIface {

    public void hello(java.lang.String method, java.lang.String param, org.apache.thrift.async.AsyncMethodCallback<java.lang.String> 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 java.lang.String hello(java.lang.String method, java.lang.String param) throws org.apache.thrift.TException
    {
      send_hello(method, param);
      return recv_hello();
    }

    public void send_hello(java.lang.String method, java.lang.String param) throws org.apache.thrift.TException
    {
      hello_args args = new hello_args();
      args.setMethod(method);
      args.setParam(param);
      sendBase("hello", args);
    }

    public java.lang.String recv_hello() throws org.apache.thrift.TException
    {
      hello_result result = new hello_result();
      receiveBase(result, "hello");
      if (result.isSetSuccess()) {
        return result.success;
      }
      throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "hello 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 hello(java.lang.String method, java.lang.String param, org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler) throws org.apache.thrift.TException {
      checkReady();
      hello_call method_call = new hello_call(method, param, resultHandler, this, ___protocolFactory, ___transport);
      this.___currentMethod = method_call;
      ___manager.call(method_call);
    }

    public static class hello_call extends org.apache.thrift.async.TAsyncMethodCall<java.lang.String> {
      private java.lang.String method;
      private java.lang.String param;
      public hello_call(java.lang.String method, java.lang.String param, org.apache.thrift.async.AsyncMethodCallback<java.lang.String> 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.method = method;
        this.param = param;
      }

      public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
        prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("hello", org.apache.thrift.protocol.TMessageType.CALL, 0));
        hello_args args = new hello_args();
        args.setMethod(method);
        args.setParam(param);
        args.write(prot);
        prot.writeMessageEnd();
      }

      public java.lang.String getResult() throws org.apache.thrift.TException {
        if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
          throw new java.lang.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_hello();
      }
    }

  }

  public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
    private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName());
    public Processor(I iface) {
      super(iface, getProcessMap(new java.util.HashMap<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
    }

    protected Processor(I iface, java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
      super(iface, processMap);
    }

    private static <I extends Iface> java.util.Map<java.lang.String,  org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends  org.apache.thrift.TBase>> processMap) {
      processMap.put("hello", new hello());
      return processMap;
    }

    public static class hello<I extends Iface> extends org.apache.thrift.ProcessFunction<I, hello_args> {
      public hello() {
        super("hello");
      }

      public hello_args getEmptyArgsInstance() {
        return new hello_args();
      }

      protected boolean isOneway() {
        return false;
      }

      @Override
      protected boolean handleRuntimeExceptions() {
        return false;
      }

      public hello_result getResult(I iface, hello_args args) throws org.apache.thrift.TException {
        hello_result result = new hello_result();
        result.success = iface.hello(args.method, args.param);
        return result;
      }
    }

  }

  public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
    private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName());
    public AsyncProcessor(I iface) {
      super(iface, getProcessMap(new java.util.HashMap<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
    }

    protected AsyncProcessor(I iface, java.util.Map<java.lang.String,  org.apache.thrift.AsyncProcessFunction<I, ? extends  org.apache.thrift.TBase, ?>> processMap) {
      super(iface, getProcessMap(processMap));
    }

    private static <I extends AsyncIface> java.util.Map<java.lang.String,  org.apache.thrift.AsyncProcessFunction<I, ? extends  org.apache.thrift.TBase,?>> getProcessMap(java.util.Map<java.lang.String,  org.apache.thrift.AsyncProcessFunction<I, ? extends  org.apache.thrift.TBase, ?>> processMap) {
      processMap.put("hello", new hello());
      return processMap;
    }

    public static class hello<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, hello_args, java.lang.String> {
      public hello() {
        super("hello");
      }

      public hello_args getEmptyArgsInstance() {
        return new hello_args();
      }

      public org.apache.thrift.async.AsyncMethodCallback<java.lang.String> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
        final org.apache.thrift.AsyncProcessFunction fcall = this;
        return new org.apache.thrift.async.AsyncMethodCallback<java.lang.String>() { 
          public void onComplete(java.lang.String o) {
            hello_result result = new hello_result();
            result.success = o;
            try {
              fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
            } catch (org.apache.thrift.transport.TTransportException e) {
              _LOGGER.error("TTransportException writing to internal frame buffer", e);
              fb.close();
            } catch (java.lang.Exception e) {
              _LOGGER.error("Exception writing to internal frame buffer", e);
              onError(e);
            }
          }
          public void onError(java.lang.Exception e) {
            byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
            org.apache.thrift.TSerializable msg;
            hello_result result = new hello_result();
            if (e instanceof org.apache.thrift.transport.TTransportException) {
              _LOGGER.error("TTransportException inside handler", e);
              fb.close();
              return;
            } else if (e instanceof org.apache.thrift.TApplicationException) {
              _LOGGER.error("TApplicationException inside handler", e);
              msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
              msg = (org.apache.thrift.TApplicationException)e;
            } else {
              _LOGGER.error("Exception inside handler", e);
              msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
              msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
            }
            try {
              fcall.sendResponse(fb,msg,msgType,seqid);
            } catch (java.lang.Exception ex) {
              _LOGGER.error("Exception writing to internal frame buffer", ex);
              fb.close();
            }
          }
        };
      }

      protected boolean isOneway() {
        return false;
      }

      public void start(I iface, hello_args args, org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler) throws org.apache.thrift.TException {
        iface.hello(args.method, args.param,resultHandler);
      }
    }

  }

  public static class hello_args implements org.apache.thrift.TBase<hello_args, hello_args._Fields>, java.io.Serializable, Cloneable, Comparable<hello_args>   {
    private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("hello_args");

    private static final org.apache.thrift.protocol.TField METHOD_FIELD_DESC = new org.apache.thrift.protocol.TField("method", org.apache.thrift.protocol.TType.STRING, (short)1);
    private static final org.apache.thrift.protocol.TField PARAM_FIELD_DESC = new org.apache.thrift.protocol.TField("param", org.apache.thrift.protocol.TType.STRING, (short)2);

    private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new hello_argsStandardSchemeFactory();
    private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new hello_argsTupleSchemeFactory();

    public java.lang.String method; // required
    public java.lang.String param; // 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 {
      METHOD((short)1, "method"),
      PARAM((short)2, "param");

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

      static {
        for (_Fields field : java.util.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: // METHOD
            return METHOD;
          case 2: // PARAM
            return PARAM;
          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 java.lang.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(java.lang.String name) {
        return byName.get(name);
      }

      private final short _thriftId;
      private final java.lang.String _fieldName;

      _Fields(short thriftId, java.lang.String fieldName) {
        _thriftId = thriftId;
        _fieldName = fieldName;
      }

      public short getThriftFieldId() {
        return _thriftId;
      }

      public java.lang.String getFieldName() {
        return _fieldName;
      }
    }

    // isset id assignments
    public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
    static {
      java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
      tmpMap.put(_Fields.METHOD, new org.apache.thrift.meta_data.FieldMetaData("method", org.apache.thrift.TFieldRequirementType.DEFAULT, 
          new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
      tmpMap.put(_Fields.PARAM, new org.apache.thrift.meta_data.FieldMetaData("param", org.apache.thrift.TFieldRequirementType.DEFAULT, 
          new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
      metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
      org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(hello_args.class, metaDataMap);
    }

    public hello_args() {
    }

    public hello_args(
      java.lang.String method,
      java.lang.String param)
    {
      this();
      this.method = method;
      this.param = param;
    }

    /**
     * Performs a deep copy on <i>other</i>.
     */
    public hello_args(hello_args other) {
      if (other.isSetMethod()) {
        this.method = other.method;
      }
      if (other.isSetParam()) {
        this.param = other.param;
      }
    }

    public hello_args deepCopy() {
      return new hello_args(this);
    }

    public void clear() {
      this.method = null;
      this.param = null;
    }

    public java.lang.String getMethod() {
      return this.method;
    }

    public hello_args setMethod(java.lang.String method) {
      this.method = method;
      return this;
    }

    public void unsetMethod() {
      this.method = null;
    }

    /** Returns true if field method is set (has been assigned a value) and false otherwise */
    public boolean isSetMethod() {
      return this.method != null;
    }

    public void setMethodIsSet(boolean value) {
      if (!value) {
        this.method = null;
      }
    }

    public java.lang.String getParam() {
      return this.param;
    }

    public hello_args setParam(java.lang.String param) {
      this.param = param;
      return this;
    }

    public void unsetParam() {
      this.param = null;
    }

    /** Returns true if field param is set (has been assigned a value) and false otherwise */
    public boolean isSetParam() {
      return this.param != null;
    }

    public void setParamIsSet(boolean value) {
      if (!value) {
        this.param = null;
      }
    }

    public void setFieldValue(_Fields field, java.lang.Object value) {
      switch (field) {
      case METHOD:
        if (value == null) {
          unsetMethod();
        } else {
          setMethod((java.lang.String)value);
        }
        break;

      case PARAM:
        if (value == null) {
          unsetParam();
        } else {
          setParam((java.lang.String)value);
        }
        break;

      }
    }

    public java.lang.Object getFieldValue(_Fields field) {
      switch (field) {
      case METHOD:
        return getMethod();

      case PARAM:
        return getParam();

      }
      throw new java.lang.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 java.lang.IllegalArgumentException();
      }

      switch (field) {
      case METHOD:
        return isSetMethod();
      case PARAM:
        return isSetParam();
      }
      throw new java.lang.IllegalStateException();
    }

    @Override
    public boolean equals(java.lang.Object that) {
      if (that == null)
        return false;
      if (that instanceof hello_args)
        return this.equals((hello_args)that);
      return false;
    }

    public boolean equals(hello_args that) {
      if (that == null)
        return false;
      if (this == that)
        return true;

      boolean this_present_method = true && this.isSetMethod();
      boolean that_present_method = true && that.isSetMethod();
      if (this_present_method || that_present_method) {
        if (!(this_present_method && that_present_method))
          return false;
        if (!this.method.equals(that.method))
          return false;
      }

      boolean this_present_param = true && this.isSetParam();
      boolean that_present_param = true && that.isSetParam();
      if (this_present_param || that_present_param) {
        if (!(this_present_param && that_present_param))
          return false;
        if (!this.param.equals(that.param))
          return false;
      }

      return true;
    }

    @Override
    public int hashCode() {
      int hashCode = 1;

      hashCode = hashCode * 8191 + ((isSetMethod()) ? 131071 : 524287);
      if (isSetMethod())
        hashCode = hashCode * 8191 + method.hashCode();

      hashCode = hashCode * 8191 + ((isSetParam()) ? 131071 : 524287);
      if (isSetParam())
        hashCode = hashCode * 8191 + param.hashCode();

      return hashCode;
    }

    public int compareTo(hello_args other) {
      if (!getClass().equals(other.getClass())) {
        return getClass().getName().compareTo(other.getClass().getName());
      }

      int lastComparison = 0;

      lastComparison = java.lang.Boolean.valueOf(isSetMethod()).compareTo(other.isSetMethod());
      if (lastComparison != 0) {
        return lastComparison;
      }
      if (isSetMethod()) {
        lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.method, other.method);
        if (lastComparison != 0) {
          return lastComparison;
        }
      }
      lastComparison = java.lang.Boolean.valueOf(isSetParam()).compareTo(other.isSetParam());
      if (lastComparison != 0) {
        return lastComparison;
      }
      if (isSetParam()) {
        lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.param, other.param);
        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 {
      scheme(iprot).read(iprot, this);
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
      scheme(oprot).write(oprot, this);
    }

    @Override
    public java.lang.String toString() {
      java.lang.StringBuilder sb = new java.lang.StringBuilder("hello_args(");
      boolean first = true;

      sb.append("method:");
      if (this.method == null) {
        sb.append("null");
      } else {
        sb.append(this.method);
      }
      first = false;
      if (!first) sb.append(", ");
      sb.append("param:");
      if (this.param == null) {
        sb.append("null");
      } else {
        sb.append(this.param);
      }
      first = false;
      sb.append(")");
      return sb.toString();
    }

    public void validate() throws org.apache.thrift.TException {
      // check for required fields
      // check for sub-struct validity
    }

    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, java.lang.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 hello_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
      public hello_argsStandardScheme getScheme() {
        return new hello_argsStandardScheme();
      }
    }

    private static class hello_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme<hello_args> {

      public void read(org.apache.thrift.protocol.TProtocol iprot, hello_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: // METHOD
              if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
                struct.method = iprot.readString();
                struct.setMethodIsSet(true);
              } else { 
                org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
              }
              break;
            case 2: // PARAM
              if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
                struct.param = iprot.readString();
                struct.setParamIsSet(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, hello_args struct) throws org.apache.thrift.TException {
        struct.validate();

        oprot.writeStructBegin(STRUCT_DESC);
        if (struct.method != null) {
          oprot.writeFieldBegin(METHOD_FIELD_DESC);
          oprot.writeString(struct.method);
          oprot.writeFieldEnd();
        }
        if (struct.param != null) {
          oprot.writeFieldBegin(PARAM_FIELD_DESC);
          oprot.writeString(struct.param);
          oprot.writeFieldEnd();
        }
        oprot.writeFieldStop();
        oprot.writeStructEnd();
      }

    }

    private static class hello_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
      public hello_argsTupleScheme getScheme() {
        return new hello_argsTupleScheme();
      }
    }

    private static class hello_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme<hello_args> {

      public void write(org.apache.thrift.protocol.TProtocol prot, hello_args struct) throws org.apache.thrift.TException {
        org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
        java.util.BitSet optionals = new java.util.BitSet();
        if (struct.isSetMethod()) {
          optionals.set(0);
        }
        if (struct.isSetParam()) {
          optionals.set(1);
        }
        oprot.writeBitSet(optionals, 2);
        if (struct.isSetMethod()) {
          oprot.writeString(struct.method);
        }
        if (struct.isSetParam()) {
          oprot.writeString(struct.param);
        }
      }

      public void read(org.apache.thrift.protocol.TProtocol prot, hello_args struct) throws org.apache.thrift.TException {
        org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
        java.util.BitSet incoming = iprot.readBitSet(2);
        if (incoming.get(0)) {
          struct.method = iprot.readString();
          struct.setMethodIsSet(true);
        }
        if (incoming.get(1)) {
          struct.param = iprot.readString();
          struct.setParamIsSet(true);
        }
      }
    }

    private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
      return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
    }
  }

  public static class hello_result implements org.apache.thrift.TBase<hello_result, hello_result._Fields>, java.io.Serializable, Cloneable, Comparable<hello_result>   {
    private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("hello_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 org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new hello_resultStandardSchemeFactory();
    private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new hello_resultTupleSchemeFactory();

    public java.lang.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 java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();

      static {
        for (_Fields field : java.util.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 java.lang.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(java.lang.String name) {
        return byName.get(name);
      }

      private final short _thriftId;
      private final java.lang.String _fieldName;

      _Fields(short thriftId, java.lang.String fieldName) {
        _thriftId = thriftId;
        _fieldName = fieldName;
      }

      public short getThriftFieldId() {
        return _thriftId;
      }

      public java.lang.String getFieldName() {
        return _fieldName;
      }
    }

    // isset id assignments
    public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
    static {
      java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.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 = java.util.Collections.unmodifiableMap(tmpMap);
      org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(hello_result.class, metaDataMap);
    }

    public hello_result() {
    }

    public hello_result(
      java.lang.String success)
    {
      this();
      this.success = success;
    }

    /**
     * Performs a deep copy on <i>other</i>.
     */
    public hello_result(hello_result other) {
      if (other.isSetSuccess()) {
        this.success = other.success;
      }
    }

    public hello_result deepCopy() {
      return new hello_result(this);
    }

    public void clear() {
      this.success = null;
    }

    public java.lang.String getSuccess() {
      return this.success;
    }

    public hello_result setSuccess(java.lang.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, java.lang.Object value) {
      switch (field) {
      case SUCCESS:
        if (value == null) {
          unsetSuccess();
        } else {
          setSuccess((java.lang.String)value);
        }
        break;

      }
    }

    public java.lang.Object getFieldValue(_Fields field) {
      switch (field) {
      case SUCCESS:
        return getSuccess();

      }
      throw new java.lang.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 java.lang.IllegalArgumentException();
      }

      switch (field) {
      case SUCCESS:
        return isSetSuccess();
      }
      throw new java.lang.IllegalStateException();
    }

    @Override
    public boolean equals(java.lang.Object that) {
      if (that == null)
        return false;
      if (that instanceof hello_result)
        return this.equals((hello_result)that);
      return false;
    }

    public boolean equals(hello_result that) {
      if (that == null)
        return false;
      if (this == that)
        return true;

      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() {
      int hashCode = 1;

      hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287);
      if (isSetSuccess())
        hashCode = hashCode * 8191 + success.hashCode();

      return hashCode;
    }

    public int compareTo(hello_result other) {
      if (!getClass().equals(other.getClass())) {
        return getClass().getName().compareTo(other.getClass().getName());
      }

      int lastComparison = 0;

      lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
      if (lastComparison != 0) {
        return lastComparison;
      }
      if (isSetSuccess()) {
        lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.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 {
      scheme(iprot).read(iprot, this);
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
      scheme(oprot).write(oprot, this);
      }

    public java.lang.String toString() {
      java.lang.StringBuilder sb = new java.lang.StringBuilder("hello_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
      // check for sub-struct validity
    }

    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, java.lang.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 hello_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
      public hello_resultStandardScheme getScheme() {
        return new hello_resultStandardScheme();
      }
    }

    private static class hello_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme<hello_result> {

      public void read(org.apache.thrift.protocol.TProtocol iprot, hello_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, hello_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 hello_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
      public hello_resultTupleScheme getScheme() {
        return new hello_resultTupleScheme();
      }
    }

    private static class hello_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme<hello_result> {

      public void write(org.apache.thrift.protocol.TProtocol prot, hello_result struct) throws org.apache.thrift.TException {
        org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
        java.util.BitSet optionals = new java.util.BitSet();
        if (struct.isSetSuccess()) {
          optionals.set(0);
        }
        oprot.writeBitSet(optionals, 1);
        if (struct.isSetSuccess()) {
          oprot.writeString(struct.success);
        }
      }

      public void read(org.apache.thrift.protocol.TProtocol prot, hello_result struct) throws org.apache.thrift.TException {
        org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
        java.util.BitSet incoming = iprot.readBitSet(1);
        if (incoming.get(0)) {
          struct.success = iprot.readString();
          struct.setSuccessIsSet(true);
        }
      }
    }

    private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
      return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
    }
  }

}

  

以上是关于Thrift 入门之helloWorld的主要内容,如果未能解决你的问题,请参考以下文章

Thrift入门之mac下的安装流程

环境初始化 Build and Install the Apache Thrift IDL Compiler Install the Platform Development Tools(代码片段

thrift入门

01.Nodejs入门之Helloworld

Apache Thrift系列详解- 概述与入门

Thrift入门