Thirft简介与用法
来源:互联网 发布:php类与对象person 编辑:程序博客网 时间:2024/06/05 20:23
转:http://blog.csdn.net/houjixin/article/details/42778335
一、 Thrift简单介绍
1.1、 Thrift是什么?能做什么?
Thrift是Facebook于2007年开发的跨语言的rpc服框架,提供多语言的编译功能,并提供多种服务器工作模式;用户通过Thrift的IDL(接口定义语言)来描述接口函数及数据类型,然后通过Thrift的编译环境生成各种语言类型的接口文件,用户可以根据自己的需要采用不同的语言开发客户端代码和服务器端代码。
例如,我想开发一个快速计算的RPC服务,它主要通过接口函数getInt对外提供服务,这个RPC服务的getInt函数使用用户传入的参数,经过复杂的计算,计算出一个整形值返回给用户;服务器端使用java语言开发,而调用客户端可以是java、c、Python等语言开发的程序,在这种应用场景下,我们只需要使用Thrift的IDL描述一下getInt函数(以.thrift为后缀的文件),然后使用Thrift的多语言编译功能,将这个IDL文件编译成C、java、python几种语言对应的“特定语言接口文件”(每种语言只需要一条简单的命令即可编译完成),这样拿到对应语言的“特定语言接口文件”之后,就可以开发客户端和服务器端的代码了,开发过程中只要接口不变,客户端和服务器端的开发可以独立的进行。
Thrift为服务器端程序提供了很多的工作模式,例如:线程池模型、非阻塞模型等等,可以根据自己的实际应用场景选择一种工作模式高效地对外提供服务;
1.2、 Thrift的相关网址和资料:
(1) Thrift的官方网站:http://thrift.apache.org/
(2) Thrift官方下载地址:http://thrift.apache.org/download
(3) Thrift官方的IDL示例文件(自己写IDL文件时可以此为参考):
https://git-wip-us.apache.org/repos/asf?p=thrift.git;a=blob_plain;f=test/ThriftTest.thrift;hb=HEAD
(4) 各种环境下搭建Thrift的方法:
http://thrift.apache.org/docs/install/
该页面中共提供了CentOS\Ubuntu\OS X\Windows几种环境下的搭建Thrift环境的方法。
二、 Thrift的使用
Thrift提供跨语言的服务框架,这种跨语言主要体现在它对多种语言的编译功能的支持,用户只需要使用IDL描述好接口函数,只需要一条简单的命令,Thrift就能够把按照IDL格式描述的接口文件翻译成各种语言版本。其实,说搭建Thrift环境的时候,实际上最麻烦的就是搭建Thrift的编译环境,Thrift的编译和通常的编译一样经过词法分析、语法分析等等最终生成对应语言的源码文件,为了能够支持对各种语言的编译,你需要下载各种语言对应的编译时使用的包;
2.1、 搭建Thrift的编译环境
本节主要介绍如何搭建Unix编译环境,搭建时有以下要求:
基本要求:
G++、boost、lex、yacc
源码安装要求:
如果使用源码安装的方式,则还需要下列工具:
Autoconf、automake、libtool、pkg-config、lex和yacc的开发版、libssl-dev
语言要求:
搭建C++编译环境:boost、libevent、zlib
搭建java编译环境:jdk、ApacheAnt
具体搭建环境时可以参考“一”中所列官网的安装方法。
2.2、 搭建JAVA下Thrift开发环境
在java环境下开发thrift的客户端或者服务器程序非常简单,只需在工程文件中加上下面三个jar包(版本可能随时有更新):
libthrift-0.9.3.jar
slf4j-api-1.7.5.jar
slf4j-simple.jar
2.3、 编写IDL文件
使用Thrift开发程序,首先要做的事情就是使用IDL对接口进行描述, 然后再使用Thrift的多语言编译能力将接口的描述文件编译成对应语言的版本,本文中将IDL对接口的描述文件称为“Thrift文件”。
(1) 编写Thrift文件
使用IDL对接口进行描述的thrift文件命名一般都是以“.thrift”作为后缀:XXX.thrift,可以在该文件的开头为该文件加上命名空间限制,格式为:namespace语言 命名空间的名字;例如:
namespace java com.thirft.service
IDL文件中对所有接口函数的描述都放在service中,service的名字可以自己指定,该名字也将被用作生成的特定语言接口文件的名字,接口函数需要对参数使用序号标号,除最后一个接口函数外,要以“,”结束对函数的描述。
Test.thrift文件
namespace java com.thirft.serviceservice ISayHello{ string sayHello(1:string param)}
通过:thrift-0.9.3.exe的目录下,打开cmd命令窗口,使用thrift-0.9.3 -r -gen java ISayHello.thrift命令生成ISayHello.java文件.
ISayHello.java文件:
/** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */package com.thirft.service;import java.util.ArrayList;import java.util.BitSet;import java.util.Collections;import java.util.EnumMap;import java.util.EnumSet;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.annotation.Generated;import org.apache.thrift.TException;import org.apache.thrift.async.AsyncMethodCallback;import org.apache.thrift.protocol.TTupleProtocol;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.server.AbstractNonblockingServer.AsyncFrameBuffer;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2017-03-14")public class ISayHello { public interface Iface { public String sayHello(String param) throws org.apache.thrift.TException; } public interface AsyncIface { public void sayHello(String param, 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 sayHello(String param) throws org.apache.thrift.TException { send_sayHello(param); return recv_sayHello(); } public void send_sayHello(String param) throws org.apache.thrift.TException { sayHello_args args = new sayHello_args(); args.setParam(param); sendBase("sayHello", args); } public String recv_sayHello() throws org.apache.thrift.TException { sayHello_result result = new sayHello_result(); receiveBase(result, "sayHello"); if (result.isSetSuccess()) { return result.success; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHello 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 sayHello(String param, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); sayHello_call method_call = new sayHello_call(param, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class sayHello_call extends org.apache.thrift.async.TAsyncMethodCall { private String param; public sayHello_call(String param, 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.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("sayHello", org.apache.thrift.protocol.TMessageType.CALL, 0)); sayHello_args args = new sayHello_args(); args.setParam(param); 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_sayHello(); } } } 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("sayHello", new sayHello()); return processMap; } public static class sayHello<I extends Iface> extends org.apache.thrift.ProcessFunction<I, sayHello_args> { public sayHello() { super("sayHello"); } public sayHello_args getEmptyArgsInstance() { return new sayHello_args(); } protected boolean isOneway() { return false; } public sayHello_result getResult(I iface, sayHello_args args) throws org.apache.thrift.TException { sayHello_result result = new sayHello_result(); result.success = iface.sayHello(args.param); 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("sayHello", new sayHello()); return processMap; } public static class sayHello<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, sayHello_args, String> { public sayHello() { super("sayHello"); } public sayHello_args getEmptyArgsInstance() { return new sayHello_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) { sayHello_result result = new sayHello_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; sayHello_result result = new sayHello_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, sayHello_args args, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws TException { iface.sayHello(args.param,resultHandler); } } } public static class sayHello_args implements org.apache.thrift.TBase<sayHello_args, sayHello_args._Fields>, java.io.Serializable, Cloneable, Comparable<sayHello_args> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_args"); 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)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new sayHello_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new sayHello_argsTupleSchemeFactory()); } public 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 { PARAM((short)1, "param"); 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: // 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 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.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 = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_args.class, metaDataMap); } public sayHello_args() { } public sayHello_args( String param) { this(); this.param = param; } /** * Performs a deep copy on <i>other</i>. */ public sayHello_args(sayHello_args other) { if (other.isSetParam()) { this.param = other.param; } } public sayHello_args deepCopy() { return new sayHello_args(this); } @Override public void clear() { this.param = null; } public String getParam() { return this.param; } public sayHello_args setParam(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, Object value) { switch (field) { case PARAM: if (value == null) { unsetParam(); } else { setParam((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PARAM: return getParam(); } 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 PARAM: return isSetParam(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof sayHello_args) return this.equals((sayHello_args)that); return false; } public boolean equals(sayHello_args that) { if (that == null) 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() { List<Object> list = new ArrayList<Object>(); boolean present_param = true && (isSetParam()); list.add(present_param); if (present_param) list.add(param); return list.hashCode(); } @Override public int compareTo(sayHello_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = 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 { 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("sayHello_args("); boolean first = true; 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, 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 sayHello_argsStandardSchemeFactory implements SchemeFactory { public sayHello_argsStandardScheme getScheme() { return new sayHello_argsStandardScheme(); } } private static class sayHello_argsStandardScheme extends StandardScheme<sayHello_args> { public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_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: // 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, sayHello_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.param != null) { oprot.writeFieldBegin(PARAM_FIELD_DESC); oprot.writeString(struct.param); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class sayHello_argsTupleSchemeFactory implements SchemeFactory { public sayHello_argsTupleScheme getScheme() { return new sayHello_argsTupleScheme(); } } private static class sayHello_argsTupleScheme extends TupleScheme<sayHello_args> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetParam()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetParam()) { oprot.writeString(struct.param); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.param = iprot.readString(); struct.setParamIsSet(true); } } } } public static class sayHello_result implements org.apache.thrift.TBase<sayHello_result, sayHello_result._Fields>, java.io.Serializable, Cloneable, Comparable<sayHello_result> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_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 sayHello_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new sayHello_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(sayHello_result.class, metaDataMap); } public sayHello_result() { } public sayHello_result( String success) { this(); this.success = success; } /** * Performs a deep copy on <i>other</i>. */ public sayHello_result(sayHello_result other) { if (other.isSetSuccess()) { this.success = other.success; } } public sayHello_result deepCopy() { return new sayHello_result(this); } @Override public void clear() { this.success = null; } public String getSuccess() { return this.success; } public sayHello_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 sayHello_result) return this.equals((sayHello_result)that); return false; } public boolean equals(sayHello_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(); } @Override public int compareTo(sayHello_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("sayHello_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 sayHello_resultStandardSchemeFactory implements SchemeFactory { public sayHello_resultStandardScheme getScheme() { return new sayHello_resultStandardScheme(); } } private static class sayHello_resultStandardScheme extends StandardScheme<sayHello_result> { public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_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, sayHello_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 sayHello_resultTupleSchemeFactory implements SchemeFactory { public sayHello_resultTupleScheme getScheme() { return new sayHello_resultTupleScheme(); } } private static class sayHello_resultTupleScheme extends TupleScheme<sayHello_result> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetSuccess()) { oprot.writeString(struct.success); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_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); } } } }}
服务端需实现ISayHello.Iface接口,在实现接口中完成自己要提供的服务,服务器端对服务接口实现的代码如下所示:
/* * 文件名:SayHelloImpl.java * 版权:Copyright 2007-2017 517na Tech. Co. Ltd. All Rights Reserved. * 描述: SayHelloImpl.java * 修改人:peiyu * 修改时间:2017年3月14日 * 修改内容:新增 */package com.thirft.service;import org.apache.thrift.TException;import com.thirft.service.ISayHello.Iface;/** * * @author peiyu */public class SayHelloImpl implements Iface{ @Override public String sayHello(String param) throws TException { System.out.println("param:"+param); return param+" say hello"; }}
(1) 编写IDL文件时需要注意的问题
[1]函数的参数要用数字依序标好,序号从1开始,形式为:“序号:参数名”;
[2]每个函数的最后要加上“,”,最后一个函数不加;
[3]在IDL中可以使用/……/添加注释
(2) IDL支持的数据类型
IDL大小写敏感,它共支持以下几种基本的数据类型:
[1]string, 字符串类型,注意是全部小写形式;例如:string aString
[2]i16, 16位整形类型,例如:i16 aI16Val;
[3]i32,32位整形类型,对应C/C++/java中的int类型;例如: I32 aIntVal
[4]i64,64位整形,对应C/C++/java中的long类型;例如:I64 aLongVal
[5]byte,8位的字符类型,对应C/C++中的char,java中的byte类型;例如:byte aByteVal
[6]bool, 布尔类型,对应C/C++中的bool,java中的boolean类型; 例如:bool aBoolVal
[7]double,双精度浮点类型,对应C/C++/java中的double类型;例如:double aDoubleVal
[8]void,空类型,对应C/C++/java中的void类型;该类型主要用作函数的返回值,例如:void testVoid(),
除上述基本类型外,ID还支持以下类型:
[1]map,map类型,例如,定义一个map对象:map
- Thirft简介与用法
- 中间件thirft的Linux部署与运用
- Thirft工作模式与协议、示例代码
- ListFragment简介与用法
- block简介与用法
- less简介与用法
- Section简介与用法分析
- BufferedInputStream与BufferedOutputStream用法简介
- 宏的用法与简介
- BufferedInputStream与BufferedOutputStream用法简介
- IOS Block简介与用法
- set与map用法简介
- BufferedInputStream与BufferedOutputStream用法简介
- BufferedInputStream与BufferedOutputStream用法简介
- BufferedInputStream与BufferedOutputStream用法简介
- c语言中的#与##的用法简介
- TRANSLATE函数与REPLACE函数用法简介
- 函数对象functor的简介与用法
- STM32f103 —— 内部flash读写
- 一些第三方的手动导入
- python 画图--简单开始及折线图
- Python操控MySql
- 区块链学堂(第二课):以太坊基本概念+Geth 安装
- Thirft简介与用法
- ALSA --- amixer控制声卡驱动实现Line-in功能
- 关于AppSplash启动优化
- tomcat启动寻找JAVA环境
- 【随笔】关于坚持
- elasticsearch 查询(match和term)
- python 画图--饼图
- Stuts2国际化
- 支持POST方式的webbench