[ToDo]Thrift学习

这里有较详细的Java项目配置过程:

http://bglmmz.iteye.com/blog/2058785

下面有Java项目的示例介绍:

http://www.tuicool.com/articles/m2EjQn

http://www.tuicool.com/articles/2YBrq23

这篇比较详细的Java项目:

http://www.micmiu.com/soa/rpc/thrift-sample/

原理详解:

http://www.cnblogs.com/brucewoo/archive/2012/06/03/2532788.html

可以借鉴以下两个页面:

http://blog.sina.com.cn/s/blog_59c4c2ed01010pwc.html

http://blog.sina.com.cn/s/blog_59c4c2ed01010pwe.html

下面这两个页面是抄的别人的:

http://blog.csdn.net/poechant/article/details/6618264

http://blog.csdn.net/poechant/article/details/6618284

Thrift使用入门(1) - Thrift概述及其安装

 

http://www.ibm.com/developerworks/cn/java/j-lo-apachethrift/

Apache Thrift - 可伸缩的跨语言服务开发框架

 

更多原理及实现,可以看:

http://dongxicheng.org/search-engine/thrift-internals/

http://dongxicheng.org/search-engine/thrift-rpc/

 

1. 在Mac机器上,直接用 brew install thrift 可安装,还没有试用。

安装在了这里:

/usr/local/Cellar/thrift/0.9.3/

 

2. 从 http://mirrors.cnnic.cn/apache/thrift/0.9.3/thrift-0.9.3.tar.gz 下载thrift

解压在m42n03机器/home/work/data/installed/,然后 ./configure --prefix=/home/work/data/installed/thrift

报错没有安装Bison,用Jumbo install bison安装

 

3.  然后 ./configure --prefix=/home/work/data/installed/thrift 就可以安装成功。

注:如果不想安排某些语言,可以加参数,比如--without-haskell,但是我安装了全部

然后make, 再之后make install

注:最后再make check运行一下。

 

4. 需要把目录加进环境变量:

export PATH=/home/work/data/installed/thrift/bin:$PATH

 

5. 在目录/home/work/data/code/thrift_demo创建demo:

首先 student.thrift

复制代码
struct Student {
1: i32 sno,
2: string sname,
3: bool ssex,
4: i16 sage,
}
service Serv {
void put(1: Student s),
}
复制代码

 

然后运行命令

thrift -r --gen cpp student.thrift  

其中 -r 表示也生成 include文件

在gen-cpp目录中生成了.cpp和.h文件。

复制代码
[gen-cpp]$ ll
total 40
-rw-rw-r--  1 work work 10164 Oct 10 10:38 Serv.cpp
-rw-rw-r--  1 work work  7642 Oct 10 10:38 Serv.h
-rw-rw-r--  1 work work  1265 Oct 10 10:38 Serv_server.skeleton.cpp
-rw-rw-r--  1 work work   261 Oct 10 10:38 student_constants.cpp
-rw-rw-r--  1 work work   347 Oct 10 10:38 student_constants.h
-rw-rw-r--  1 work work  3934 Oct 10 10:38 student_types.cpp
-rw-rw-r--  1 work work  1767 Oct 10 10:38 student_types.h
复制代码

在其中的Serv_server.skeleton.cpp里面,写业务代码,其中有这么一段。加了一句"_return = "Hello here!";":

复制代码
class ServHandler : virtual public ServIf {
 public:
  ServHandler() {
    // Your initialization goes here
  }

  void put(std::string& _return, const Student& s) {
    // Your implementation goes here
_return = "Hello here!"; printf("put\n"); } };
复制代码

但是编译的时候,不知道INCPATH和LDLIBRARY路径在哪里。

安装的目录里面只有bin目录,上网查了一下,貌似要安装boost。

另开一篇文章,说明boost的安装使用。

下面是从公司wiki上找到的一个说明。

复制代码
boost & thrift安装步骤
1.    boost安装
cd /usr/local
tar zxvf boost_1_49_0.tar.gz
./bootstrap.sh --prefix=/usr/local/boost_1_49_0
./b2 install


2.    thrift安装
tar zxvf thrift-0.8.0.tar.gz
cd thrift-0.8.0
./configure --with-boost=/usr/local/boost_1_49_0 --prefix=/home/work/local/thrift-0.8.0
make
make install


make如有下面报错:
…: tr1/functional: No such file or directory
…
make[4]: Leaving directory `/home/work/thrift-0.8.0/lib/cpp'
make[3]: *** [all-recursive] Error 1
make[3]: Leaving directory `/home/work/thrift-0.8.0/lib/cpp'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/work/thrift-0.8.0/lib'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/work/thrift-0.8.0'
make: *** [all] Error 2

则修改如下3个文件:
vi lib/cpp/src/concurrency/ThreadManager.h
24 #include <boost/tr1/tr1/functional>

vi lib/cpp/src/async/TAsyncChannel.h
23 #include <boost/tr1/tr1/functional>

vi lib/cpp/src/async/TAsyncChannel.cpp
21 #include <boost/tr1/tr1/functional>
复制代码

 

上面C++程序需要boost才能完成,所以先看Java版本吧。

打开Intellij,新建一个Maven项目,位置在 /Users/baidu/Documents/Data/Work/Code/Self/thrift-demo

其中pom.xml如下:

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<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.thrift</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.8</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>thrift-demo</finalName>
    </build>

</project>
复制代码

在目录中新建 demoHello.thrift

复制代码
namespace java com.thrift.demo

struct Student {
1: i32 sno,
2: string sname,
3: bool ssex,
4: i16 sage,
}
service  HelloWorldService {
    string put(1: Student s),
}
 
复制代码

运行命令:

thrift -r -gen java ./demoHello.thrift 

在Java项目里创建package: com.thrift.demo

把上面生成的文件放进这个目录:

 

报一些语法错误,有一个是由于thrift版本不够,升级了版本就可以。另一个是需要把不少@Override 都去掉。

然后创建两个文件,分别是HelloWorldImpl和HelloServerDemo:

HelloWorldImpl

复制代码
package com.thrift.demo;

/**
 * Created by baidu on 16/10/10.
 */
public class HelloWorldImpl implements HelloWorldService.Iface {

    public String put(Student s) {
        return "Hi," + s.getSname() + ", Welcome!";
    }
}
复制代码

HelloServerDemo

复制代码
package com.thrift.demo;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;

/**
 * Created by baidu on 16/10/10.
 */
public class HelloServerDemo {
    public static final int SERVER_PORT = 8090;

    public void startServer() {
        try {
            System.out.println("HelloServer start ...");

            TProcessor tProcessor = new HelloWorldService.Processor<HelloWorldService.Iface>(
                    new HelloWorldImpl()
            );
            TServerSocket serverTransport = new TServerSocket(SERVER_PORT);
            TServer.Args tArgs = new TServer.Args(serverTransport);
            tArgs.processor(tProcessor);
            tArgs.protocolFactory(new TBinaryProtocol.Factory());

            TServer server = new TSimpleServer(tArgs);
            server.serve();

        }
        catch (Exception e) {
            System.out.println("Server Error!");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HelloServerDemo server = new HelloServerDemo();
        server.startServer();
    }
}
复制代码

打开File -> Project Structure -> Artifacts点击“+”,选择“Jar”,然后选择"from modules with dependencies"。

在配置窗口中配置"Main Class"。选择“Main Class”后,选择“copy to the output  and link via manifest”,配置“Directory for META-INF/MAINFEST.MF”,此项配置的缺省值是:xxx\src\main\java,需要改成:xxx\src\main\resources,如果不这样修改,打成的jar包里没有包含META-INF/MAINFEST.MF文件,这个应该是个IDEA的BUG。(开始我没有改,使用jar包的时候,报错找不到manifest)

要勾选“Build on make”。

然后make的时候,在out目录(/Users/baidu/Documents/Data/Work/Code/Self/thrift-demo/out/artifacts/thrift_demo_jar) 就能够看到jar包。

然后在这个目录,运行:

java -jar thrift-demo.jar

得到打印结果:

$ java -jar thrift-demo.jar
HelloServer start ...
SLF4J: The requested version 1.5.8 by your slf4j binding is not compatible with [1.6, 1.7]
SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.

 

现在写客户端:

开始写在一个project里面,但是看起来不行,创建artifact的时候报错,已存在Manifest.md。所以就另创建了一个工程。可以在Intellij里面新建一个project,然后在新窗口打开,就可以两个工程的窗口都开着了。

跟服务器端基本一致。pom.xml内容如下:

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<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.thrift</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.8</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>thrift-demo</finalName>
    </build>

</project>
复制代码

在java目录创建 package com.thrift.demo,把两个Interface文件拉进来:

Student和HelloWorldService,一个对应Protocol,一个对应Service。

然后新创建一个class HelloClient,内容如下:

原来的内容贴错了,下面是真正的HelloClient文件:

复制代码
package com.thrift.demo;

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;

/**
 * Created by baidu on 16/10/10.
 */
public class HelloClient {
    public static final String SERVER_IP = "localhost";
    public static final int SERVER_PORT = 8090;
    public static final int TIMEOUT = 30000;

    public void startClient(String userName) {
        TTransport transp = null;
        try {

            transp = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
            TProtocol protocol = new TBinaryProtocol(transp);
            HelloWorldService.Client client = new HelloWorldService.Client(protocol);
            transp.open();
            Student stdt = new Student(1, userName, true, (short)1);
            String result = client.put(stdt);
            System.out.printf("Thrift client result=%s\n", result);

        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            if (null != transp) {
                transp.close();
            }
        }
    }

    public static void main(String[] args) {
        HelloClient client = new HelloClient();
        client.startClient("Tom");
    }
}
复制代码

 

另外还有Student文件:

复制代码
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.thrift.demo;

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 org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
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 javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-10-10")
public class Student implements org.apache.thrift.TBase<Student, Student._Fields>, java.io.Serializable, Cloneable, Comparable<Student> {
    private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Student");

    private static final org.apache.thrift.protocol.TField SNO_FIELD_DESC = new org.apache.thrift.protocol.TField("sno", org.apache.thrift.protocol.TType.I32, (short)1);
    private static final org.apache.thrift.protocol.TField SNAME_FIELD_DESC = new org.apache.thrift.protocol.TField("sname", org.apache.thrift.protocol.TType.STRING, (short)2);
    private static final org.apache.thrift.protocol.TField SSEX_FIELD_DESC = new org.apache.thrift.protocol.TField("ssex", org.apache.thrift.protocol.TType.BOOL, (short)3);
    private static final org.apache.thrift.protocol.TField SAGE_FIELD_DESC = new org.apache.thrift.protocol.TField("sage", org.apache.thrift.protocol.TType.I16, (short)4);

    private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
    static {
        schemes.put(StandardScheme.class, new StudentStandardSchemeFactory());
        schemes.put(TupleScheme.class, new StudentTupleSchemeFactory());
    }

    public int sno; // required
    public String sname; // required
    public boolean ssex; // required
    public short sage; // 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 {
        SNO((short)1, "sno"),
        SNAME((short)2, "sname"),
        SSEX((short)3, "ssex"),
        SAGE((short)4, "sage");

        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: // SNO
                    return SNO;
                case 2: // SNAME
                    return SNAME;
                case 3: // SSEX
                    return SSEX;
                case 4: // SAGE
                    return SAGE;
                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
    private static final int __SNO_ISSET_ID = 0;
    private static final int __SSEX_ISSET_ID = 1;
    private static final int __SAGE_ISSET_ID = 2;
    private byte __isset_bitfield = 0;
    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.SNO, new org.apache.thrift.meta_data.FieldMetaData("sno", org.apache.thrift.TFieldRequirementType.DEFAULT,
                new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
        tmpMap.put(_Fields.SNAME, new org.apache.thrift.meta_data.FieldMetaData("sname", org.apache.thrift.TFieldRequirementType.DEFAULT,
                new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
        tmpMap.put(_Fields.SSEX, new org.apache.thrift.meta_data.FieldMetaData("ssex", org.apache.thrift.TFieldRequirementType.DEFAULT,
                new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
        tmpMap.put(_Fields.SAGE, new org.apache.thrift.meta_data.FieldMetaData("sage", org.apache.thrift.TFieldRequirementType.DEFAULT,
                new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
        metaDataMap = Collections.unmodifiableMap(tmpMap);
        org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Student.class, metaDataMap);
    }

    public Student() {
    }

    public Student(
            int sno,
            String sname,
            boolean ssex,
            short sage)
    {
        this();
        this.sno = sno;
        setSnoIsSet(true);
        this.sname = sname;
        this.ssex = ssex;
        setSsexIsSet(true);
        this.sage = sage;
        setSageIsSet(true);
    }

    /**
     * Performs a deep copy on <i>other</i>.
     */
    public Student(Student other) {
        __isset_bitfield = other.__isset_bitfield;
        this.sno = other.sno;
        if (other.isSetSname()) {
            this.sname = other.sname;
        }
        this.ssex = other.ssex;
        this.sage = other.sage;
    }

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


    public void clear() {
        setSnoIsSet(false);
        this.sno = 0;
        this.sname = null;
        setSsexIsSet(false);
        this.ssex = false;
        setSageIsSet(false);
        this.sage = 0;
    }

    public int getSno() {
        return this.sno;
    }

    public Student setSno(int sno) {
        this.sno = sno;
        setSnoIsSet(true);
        return this;
    }

    public void unsetSno() {
        __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SNO_ISSET_ID);
    }

    /** Returns true if field sno is set (has been assigned a value) and false otherwise */
    public boolean isSetSno() {
        return EncodingUtils.testBit(__isset_bitfield, __SNO_ISSET_ID);
    }

    public void setSnoIsSet(boolean value) {
        __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SNO_ISSET_ID, value);
    }

    public String getSname() {
        return this.sname;
    }

    public Student setSname(String sname) {
        this.sname = sname;
        return this;
    }

    public void unsetSname() {
        this.sname = null;
    }

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

    public void setSnameIsSet(boolean value) {
        if (!value) {
            this.sname = null;
        }
    }

    public boolean isSsex() {
        return this.ssex;
    }

    public Student setSsex(boolean ssex) {
        this.ssex = ssex;
        setSsexIsSet(true);
        return this;
    }

    public void unsetSsex() {
        __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SSEX_ISSET_ID);
    }

    /** Returns true if field ssex is set (has been assigned a value) and false otherwise */
    public boolean isSetSsex() {
        return EncodingUtils.testBit(__isset_bitfield, __SSEX_ISSET_ID);
    }

    public void setSsexIsSet(boolean value) {
        __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SSEX_ISSET_ID, value);
    }

    public short getSage() {
        return this.sage;
    }

    public Student setSage(short sage) {
        this.sage = sage;
        setSageIsSet(true);
        return this;
    }

    public void unsetSage() {
        __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SAGE_ISSET_ID);
    }

    /** Returns true if field sage is set (has been assigned a value) and false otherwise */
    public boolean isSetSage() {
        return EncodingUtils.testBit(__isset_bitfield, __SAGE_ISSET_ID);
    }

    public void setSageIsSet(boolean value) {
        __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SAGE_ISSET_ID, value);
    }

    public void setFieldValue(_Fields field, Object value) {
        switch (field) {
            case SNO:
                if (value == null) {
                    unsetSno();
                } else {
                    setSno((Integer)value);
                }
                break;

            case SNAME:
                if (value == null) {
                    unsetSname();
                } else {
                    setSname((String)value);
                }
                break;

            case SSEX:
                if (value == null) {
                    unsetSsex();
                } else {
                    setSsex((Boolean)value);
                }
                break;

            case SAGE:
                if (value == null) {
                    unsetSage();
                } else {
                    setSage((Short)value);
                }
                break;

        }
    }

    public Object getFieldValue(_Fields field) {
        switch (field) {
            case SNO:
                return getSno();

            case SNAME:
                return getSname();

            case SSEX:
                return isSsex();

            case SAGE:
                return getSage();

        }
        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 SNO:
                return isSetSno();
            case SNAME:
                return isSetSname();
            case SSEX:
                return isSetSsex();
            case SAGE:
                return isSetSage();
        }
        throw new IllegalStateException();
    }

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

    public boolean equals(Student that) {
        if (that == null)
            return false;

        boolean this_present_sno = true;
        boolean that_present_sno = true;
        if (this_present_sno || that_present_sno) {
            if (!(this_present_sno && that_present_sno))
                return false;
            if (this.sno != that.sno)
                return false;
        }

        boolean this_present_sname = true && this.isSetSname();
        boolean that_present_sname = true && that.isSetSname();
        if (this_present_sname || that_present_sname) {
            if (!(this_present_sname && that_present_sname))
                return false;
            if (!this.sname.equals(that.sname))
                return false;
        }

        boolean this_present_ssex = true;
        boolean that_present_ssex = true;
        if (this_present_ssex || that_present_ssex) {
            if (!(this_present_ssex && that_present_ssex))
                return false;
            if (this.ssex != that.ssex)
                return false;
        }

        boolean this_present_sage = true;
        boolean that_present_sage = true;
        if (this_present_sage || that_present_sage) {
            if (!(this_present_sage && that_present_sage))
                return false;
            if (this.sage != that.sage)
                return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        List<Object> list = new ArrayList<Object>();

        boolean present_sno = true;
        list.add(present_sno);
        if (present_sno)
            list.add(sno);

        boolean present_sname = true && (isSetSname());
        list.add(present_sname);
        if (present_sname)
            list.add(sname);

        boolean present_ssex = true;
        list.add(present_ssex);
        if (present_ssex)
            list.add(ssex);

        boolean present_sage = true;
        list.add(present_sage);
        if (present_sage)
            list.add(sage);

        return list.hashCode();
    }


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

        int lastComparison = 0;

        lastComparison = Boolean.valueOf(isSetSno()).compareTo(other.isSetSno());
        if (lastComparison != 0) {
            return lastComparison;
        }
        if (isSetSno()) {
            lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.sno, other.sno);
            if (lastComparison != 0) {
                return lastComparison;
            }
        }
        lastComparison = Boolean.valueOf(isSetSname()).compareTo(other.isSetSname());
        if (lastComparison != 0) {
            return lastComparison;
        }
        if (isSetSname()) {
            lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.sname, other.sname);
            if (lastComparison != 0) {
                return lastComparison;
            }
        }
        lastComparison = Boolean.valueOf(isSetSsex()).compareTo(other.isSetSsex());
        if (lastComparison != 0) {
            return lastComparison;
        }
        if (isSetSsex()) {
            lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ssex, other.ssex);
            if (lastComparison != 0) {
                return lastComparison;
            }
        }
        lastComparison = Boolean.valueOf(isSetSage()).compareTo(other.isSetSage());
        if (lastComparison != 0) {
            return lastComparison;
        }
        if (isSetSage()) {
            lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.sage, other.sage);
            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("Student(");
        boolean first = true;

        sb.append("sno:");
        sb.append(this.sno);
        first = false;
        if (!first) sb.append(", ");
        sb.append("sname:");
        if (this.sname == null) {
            sb.append("null");
        } else {
            sb.append(this.sname);
        }
        first = false;
        if (!first) sb.append(", ");
        sb.append("ssex:");
        sb.append(this.ssex);
        first = false;
        if (!first) sb.append(", ");
        sb.append("sage:");
        sb.append(this.sage);
        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, ClassNotFoundException {
        try {
            // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
            __isset_bitfield = 0;
            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 StudentStandardSchemeFactory implements SchemeFactory {
        public StudentStandardScheme getScheme() {
            return new StudentStandardScheme();
        }
    }

    private static class StudentStandardScheme extends StandardScheme<Student> {

        public void read(org.apache.thrift.protocol.TProtocol iprot, Student 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: // SNO
                        if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
                            struct.sno = iprot.readI32();
                            struct.setSnoIsSet(true);
                        } else {
                            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
                        }
                        break;
                    case 2: // SNAME
                        if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
                            struct.sname = iprot.readString();
                            struct.setSnameIsSet(true);
                        } else {
                            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
                        }
                        break;
                    case 3: // SSEX
                        if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
                            struct.ssex = iprot.readBool();
                            struct.setSsexIsSet(true);
                        } else {
                            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
                        }
                        break;
                    case 4: // SAGE
                        if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
                            struct.sage = iprot.readI16();
                            struct.setSageIsSet(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, Student struct) throws org.apache.thrift.TException {
            struct.validate();

            oprot.writeStructBegin(STRUCT_DESC);
            oprot.writeFieldBegin(SNO_FIELD_DESC);
            oprot.writeI32(struct.sno);
            oprot.writeFieldEnd();
            if (struct.sname != null) {
                oprot.writeFieldBegin(SNAME_FIELD_DESC);
                oprot.writeString(struct.sname);
                oprot.writeFieldEnd();
            }
            oprot.writeFieldBegin(SSEX_FIELD_DESC);
            oprot.writeBool(struct.ssex);
            oprot.writeFieldEnd();
            oprot.writeFieldBegin(SAGE_FIELD_DESC);
            oprot.writeI16(struct.sage);
            oprot.writeFieldEnd();
            oprot.writeFieldStop();
            oprot.writeStructEnd();
        }

    }

    private static class StudentTupleSchemeFactory implements SchemeFactory {
        public StudentTupleScheme getScheme() {
            return new StudentTupleScheme();
        }
    }

    private static class StudentTupleScheme extends TupleScheme<Student> {


        public void write(org.apache.thrift.protocol.TProtocol prot, Student struct) throws org.apache.thrift.TException {
            TTupleProtocol oprot = (TTupleProtocol) prot;
            BitSet optionals = new BitSet();
            if (struct.isSetSno()) {
                optionals.set(0);
            }
            if (struct.isSetSname()) {
                optionals.set(1);
            }
            if (struct.isSetSsex()) {
                optionals.set(2);
            }
            if (struct.isSetSage()) {
                optionals.set(3);
            }
            oprot.writeBitSet(optionals, 4);
            if (struct.isSetSno()) {
                oprot.writeI32(struct.sno);
            }
            if (struct.isSetSname()) {
                oprot.writeString(struct.sname);
            }
            if (struct.isSetSsex()) {
                oprot.writeBool(struct.ssex);
            }
            if (struct.isSetSage()) {
                oprot.writeI16(struct.sage);
            }
        }


        public void read(org.apache.thrift.protocol.TProtocol prot, Student struct) throws org.apache.thrift.TException {
            TTupleProtocol iprot = (TTupleProtocol) prot;
            BitSet incoming = iprot.readBitSet(4);
            if (incoming.get(0)) {
                struct.sno = iprot.readI32();
                struct.setSnoIsSet(true);
            }
            if (incoming.get(1)) {
                struct.sname = iprot.readString();
                struct.setSnameIsSet(true);
            }
            if (incoming.get(2)) {
                struct.ssex = iprot.readBool();
                struct.setSsexIsSet(true);
            }
            if (incoming.get(3)) {
                struct.sage = iprot.readI16();
                struct.setSageIsSet(true);
            }
        }
    }

}
View Code
复制代码

还有HelloWorldService文件:

复制代码
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.thrift.demo;

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 org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
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 javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-10-10")
public class HelloWorldService {

    public interface Iface {

        public String put(Student s) throws org.apache.thrift.TException;

    }

    public interface AsyncIface {

        public void put(Student s, org.apache.thrift.async.AsyncMethodCallback 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 put(Student s) throws org.apache.thrift.TException
        {
            send_put(s);
            return recv_put();
        }

        public void send_put(Student s) throws org.apache.thrift.TException
        {
            put_args args = new put_args();
            args.setS(s);
            sendBase("put", args);
        }

        public String recv_put() throws org.apache.thrift.TException
        {
            put_result result = new put_result();
            receiveBase(result, "put");
            if (result.isSetSuccess()) {
                return result.success;
            }
            throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "put 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 put(Student s, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
            checkReady();
            put_call method_call = new put_call(s, resultHandler, this, ___protocolFactory, ___transport);
            this.___currentMethod = method_call;
            ___manager.call(method_call);
        }

        public static class put_call extends org.apache.thrift.async.TAsyncMethodCall {
            private Student s;
            public put_call(Student s, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
                super(client, protocolFactory, transport, resultHandler, false);
                this.s = s;
            }

            public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
                prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("put", org.apache.thrift.protocol.TMessageType.CALL, 0));
                put_args args = new put_args();
                args.setS(s);
                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_put();
            }
        }

    }

    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("put", new put());
            return processMap;
        }

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

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

            protected boolean isOneway() {
                return false;
            }

            public put_result getResult(I iface, put_args args) throws org.apache.thrift.TException {
                put_result result = new put_result();
                result.success = iface.put(args.s);
                return result;
            }
        }

    }

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

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

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

        public static class put<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, put_args, String> {
            public put() {
                super("put");
            }

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

            public AsyncMethodCallback<String> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
                final org.apache.thrift.AsyncProcessFunction fcall = this;
                return new AsyncMethodCallback<String>() {
                    public void onComplete(String o) {
                        put_result result = new put_result();
                        result.success = o;
                        try {
                            fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
                            return;
                        } catch (Exception e) {
                            LOGGER.error("Exception writing to internal frame buffer", e);
                        }
                        fb.close();
                    }
                    public void onError(Exception e) {
                        byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
                        org.apache.thrift.TBase msg;
                        put_result result = new put_result();
                        {
                            msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
                            msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
                        }
                        try {
                            fcall.sendResponse(fb,msg,msgType,seqid);
                            return;
                        } catch (Exception ex) {
                            LOGGER.error("Exception writing to internal frame buffer", ex);
                        }
                        fb.close();
                    }
                };
            }

            protected boolean isOneway() {
                return false;
            }

            public void start(I iface, put_args args, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws TException {
                iface.put(args.s,resultHandler);
            }
        }

    }

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

        private static final org.apache.thrift.protocol.TField S_FIELD_DESC = new org.apache.thrift.protocol.TField("s", org.apache.thrift.protocol.TType.STRUCT, (short)1);

        private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
        static {
            schemes.put(StandardScheme.class, new put_argsStandardSchemeFactory());
            schemes.put(TupleScheme.class, new put_argsTupleSchemeFactory());
        }

        public Student s; // 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 {
            S((short)1, "s");

            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: // S
                        return S;
                    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.S, new org.apache.thrift.meta_data.FieldMetaData("s", org.apache.thrift.TFieldRequirementType.DEFAULT,
                    new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Student.class)));
            metaDataMap = Collections.unmodifiableMap(tmpMap);
            org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(put_args.class, metaDataMap);
        }

        public put_args() {
        }

        public put_args(
                Student s)
        {
            this();
            this.s = s;
        }

        /**
         * Performs a deep copy on <i>other</i>.
         */
        public put_args(put_args other) {
            if (other.isSetS()) {
                this.s = new Student(other.s);
            }
        }

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


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

        public Student getS() {
            return this.s;
        }

        public put_args setS(Student s) {
            this.s = s;
            return this;
        }

        public void unsetS() {
            this.s = null;
        }

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

        public void setSIsSet(boolean value) {
            if (!value) {
                this.s = null;
            }
        }

        public void setFieldValue(_Fields field, Object value) {
            switch (field) {
                case S:
                    if (value == null) {
                        unsetS();
                    } else {
                        setS((Student)value);
                    }
                    break;

            }
        }

        public Object getFieldValue(_Fields field) {
            switch (field) {
                case S:
                    return getS();

            }
            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 S:
                    return isSetS();
            }
            throw new IllegalStateException();
        }

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

        public boolean equals(put_args that) {
            if (that == null)
                return false;

            boolean this_present_s = true && this.isSetS();
            boolean that_present_s = true && that.isSetS();
            if (this_present_s || that_present_s) {
                if (!(this_present_s && that_present_s))
                    return false;
                if (!this.s.equals(that.s))
                    return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            List<Object> list = new ArrayList<Object>();

            boolean present_s = true && (isSetS());
            list.add(present_s);
            if (present_s)
                list.add(s);

            return list.hashCode();
        }


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

            int lastComparison = 0;

            lastComparison = Boolean.valueOf(isSetS()).compareTo(other.isSetS());
            if (lastComparison != 0) {
                return lastComparison;
            }
            if (isSetS()) {
                lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.s, other.s);
                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("put_args(");
            boolean first = true;

            sb.append("s:");
            if (this.s == null) {
                sb.append("null");
            } else {
                sb.append(this.s);
            }
            first = false;
            sb.append(")");
            return sb.toString();
        }

        public void validate() throws org.apache.thrift.TException {
            // check for required fields
            // check for sub-struct validity
            if (s != null) {
                s.validate();
            }
        }

        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 put_argsStandardSchemeFactory implements SchemeFactory {
            public put_argsStandardScheme getScheme() {
                return new put_argsStandardScheme();
            }
        }

        private static class put_argsStandardScheme extends StandardScheme<put_args> {

            public void read(org.apache.thrift.protocol.TProtocol iprot, put_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: // S
                            if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
                                struct.s = new Student();
                                struct.s.read(iprot);
                                struct.setSIsSet(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, put_args struct) throws org.apache.thrift.TException {
                struct.validate();

                oprot.writeStructBegin(STRUCT_DESC);
                if (struct.s != null) {
                    oprot.writeFieldBegin(S_FIELD_DESC);
                    struct.s.write(oprot);
                    oprot.writeFieldEnd();
                }
                oprot.writeFieldStop();
                oprot.writeStructEnd();
            }

        }

        private static class put_argsTupleSchemeFactory implements SchemeFactory {
            public put_argsTupleScheme getScheme() {
                return new put_argsTupleScheme();
            }
        }

        private static class put_argsTupleScheme extends TupleScheme<put_args> {


            public void write(org.apache.thrift.protocol.TProtocol prot, put_args struct) throws org.apache.thrift.TException {
                TTupleProtocol oprot = (TTupleProtocol) prot;
                BitSet optionals = new BitSet();
                if (struct.isSetS()) {
                    optionals.set(0);
                }
                oprot.writeBitSet(optionals, 1);
                if (struct.isSetS()) {
                    struct.s.write(oprot);
                }
            }


            public void read(org.apache.thrift.protocol.TProtocol prot, put_args struct) throws org.apache.thrift.TException {
                TTupleProtocol iprot = (TTupleProtocol) prot;
                BitSet incoming = iprot.readBitSet(1);
                if (incoming.get(0)) {
                    struct.s = new Student();
                    struct.s.read(iprot);
                    struct.setSIsSet(true);
                }
            }
        }

    }

    public static class put_result implements org.apache.thrift.TBase<put_result, put_result._Fields>, java.io.Serializable, Cloneable, Comparable<put_result>   {
        private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("put_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 put_resultStandardSchemeFactory());
            schemes.put(TupleScheme.class, new put_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(put_result.class, metaDataMap);
        }

        public put_result() {
        }

        public put_result(
                String success)
        {
            this();
            this.success = success;
        }

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

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


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

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

        public put_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 put_result)
                return this.equals((put_result)that);
            return false;
        }

        public boolean equals(put_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() {
            List<Object> list = new ArrayList<Object>();

            boolean present_success = true && (isSetSuccess());
            list.add(present_success);
            if (present_success)
                list.add(success);

            return list.hashCode();
        }


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

            int lastComparison = 0;

            lastComparison = 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 {
            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("put_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, 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 put_resultStandardSchemeFactory implements SchemeFactory {
            public put_resultStandardScheme getScheme() {
                return new put_resultStandardScheme();
            }
        }

        private static class put_resultStandardScheme extends StandardScheme<put_result> {

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

        private static class put_resultTupleScheme extends TupleScheme<put_result> {


            public void write(org.apache.thrift.protocol.TProtocol prot, put_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);
                }
            }


            public void read(org.apache.thrift.protocol.TProtocol prot, put_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);
                }
            }
        }

    }

}
View Code
复制代码

 

在File->Project Structure里面的Artifacts新建一个jar包,步骤同Server端。

然后就可以运行程序了。

 

服务器端目录:

/Users/baidu/Documents/Data/Work/Code/Self/thrift-demo/out/artifacts/thrift_demo_jar

运行结果:

$ java -jar thrift-demo.jar
HelloServer start ...
SLF4J: The requested version 1.5.8 by your slf4j binding is not compatible with [1.6, 1.7]
SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.
Get msg with Student Tom
Get msg with Student Tom

客户端目录:

/Users/baidu/Documents/Data/Work/Code/Self/thrift-client/out/artifacts/thrift_client_jar

运行结果:

复制代码
$ java -jar thrift-client.jar 
SLF4J: The requested version 1.5.8 by your slf4j binding is not compatible with [1.6, 1.7]
SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.
Thrift client result=Hi,Tom, Welcome!

$ java -jar thrift-client.jar 
SLF4J: The requested version 1.5.8 by your slf4j binding is not compatible with [1.6, 1.7]
SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.
Thrift client result=Hi,Tom, Welcome!
复制代码

 

posted @   blcblc  阅读(442)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示