Thrift 介紹及java實例
Thrift最初由facebook開發,07年四月開放源碼,08年5月進入apache孵化器。thrift允許你定義一個簡單的定義文件中的數據類型和服務接口。以作為輸入文件,編譯器生成代碼用來方便地生成RPC客戶端和服務器通信的無縫跨編程語言。
官網地址: thrift.apache.org
推薦值得一看的文章:
http://jnb.ociweb.com/jnb/jnbJun2009.html
http://wiki.apache.org/thrift
http://thrift.apache.org/static/files/thrift-20070401.pdf
- Thrift 基礎架構
Thrift是一個服務端和客戶端的架構體系,就是socket傳輸,Thrift 具有自己內部定義的傳輸協議規范(TProtocol)和傳輸數據標准(TTransports),通過IDL腳本對傳輸數據的數據結構(struct) 和傳輸數據的業務邏輯(service)根據不同的運行環境快速的構建相應的代碼,並且通過自己內部的序列化機制對傳輸的數據進行簡化和壓縮提高高並發、 大型系統中數據交互的成本,下圖描繪了Thrift的整體架構,分為6個部分:
1.你的業務邏輯實現(You Code)
2.客戶端和服務端對應的Service
3.執行讀寫操作的計算結果
4.TProtocol
5.TTransports
6.底層I/O通信
- Thrift 軟件棧

評注:
Transport: 傳輸層,定義數據傳輸方式,可以為TCP/IP傳輸,內存共享或者文件共享等
protocol: 協議層, 定義數據傳輸格式,可以為二進制或者XML等
Processor: 處理層, 這部分由定義的idl來生成, 封裝了協議輸入輸出流, 並委托給用戶實現的handler進行處理.
Server: 服務層, 整合上述組件, 提供網絡模型(單線程/多線程/事件驅動), 最終形成真正的服務.
- Thrift腳本的數據類型
bool Boolean, one byte
byte Signed byte
i16 Signed 16-bit integer
i32 Signed 32-bit integer
i64 Signed 64-bit integer
double 64-bit floating point value
string String
binary Blob (byte array)
* Struct:結構體類型
* Container:容器類型,即List、Set、Map
map<t1,t2> Map from one type to another
list<t1> Ordered list of one type
set<t1> Set of unique elements of one type
* Exception:異常類型
* Service: 定義對象的接口,和一系列方法
- 協議
* TBinaryProtocol – 二進制編碼格式進行數據傳輸。
* TCompactProtocol – 這種協議非常有效的,使用Variable-Length Quantity (VLQ) 編碼對數據進行壓縮。
* TJSONProtocol – 使用JSON的數據編碼協議進行數據傳輸。
* TSimpleJSONProtocol – 這種節約只提供JSON只寫的協議,適用於通過腳本語言解析
* TDebugProtocol – 在開發的過程中幫助開發人員調試用的,以文本的形式展現方便閱讀。
- 傳輸層
* TFramedTransport- 使用非阻塞方式,按塊的大小,進行傳輸,類似於Java中的NIO。
* TFileTransport- 顧名思義按照文件的方式進程傳輸,雖然這種方式不提供Java的實現,但是實現起來非常簡單。
* TMemoryTransport- 使用內存I/O,就好比Java中的ByteArrayOutputStream實現。
* TZlibTransport- 使用執行zlib壓縮,不提供Java的實現。
- Thrift 高性能網絡服務模型
TSimpleServer/TThreadPoolServer是阻塞服務模型
TNonblockingServer/THsHaServer/TThreadedSelectotServer是非阻塞服務模型(NIO)
2). TServer抽象類的定義
內部靜態類Args的定義, 用於TServer類用於串聯軟件棧(傳輸層, 協議層, 處理層)
-
public abstract class TServer {
-
public static class Args extends AbstractServerArgs<Args> {
-
public Args(TServerTransport transport) {
-
super(transport);
-
}
-
}
-
-
public static abstract class AbstractServerArgs<T extends AbstractServerArgs<T>> {
-
public AbstractServerArgs(TServerTransport transport);
-
public T processorFactory(TProcessorFactory factory);
-
public T processor(TProcessor processor);
-
public T transportFactory(TTransportFactory factory);
-
public T protocolFactory(TProtocolFactory factory);
-
}
-
}
-
public abstract class TServer {
-
public abstract void serve();
-
public void stop();
-
-
public boolean isServing();
-
public void setServerEventHandler(TServerEventHandler eventHandler);
-
}
各種服務模型介紹如下:
* TSimpleServer - 單線程服務器端使用標准的堵塞式I/O,只適合測試開發使用。抽象代碼描述如下:
-
// *) server socket進行監聽
-
serverSocket.listen();
-
while ( isServing() ) {
-
// *) 接受socket鏈接
-
client = serverSocket.accept();
-
// *) 封裝處理器
-
processor = factory.getProcess(client);
-
while ( true ) {
-
// *) 阻塞處理rpc的輸入/輸出
-
if ( !processor.process(input, output) ) {
-
break;
-
}
-
}
-
}
* TThreadPoolServer - 多線程服務器端使用標准的堵塞式I/O。引入了線程池,實現的模型是One Thread Per Connection。

線程池代碼片段如下:
-
private static ExecutorService createDefaultExecutorService(Args args) {
-
SynchronousQueue<Runnable> executorQueue =
-
new SynchronousQueue<Runnable>();
-
return new ThreadPoolExecutor(args.minWorkerThreads,
-
args.maxWorkerThreads,
-
60,
-
TimeUnit.SECONDS,
-
executorQueue);
-
}
采用同步隊列(SynchronousQueue), 線程池采用能線程數可伸縮的模式.
主線程循環:
-
setServing( true);
-
while (!stopped_) {
-
try {
-
TTransport client = serverTransport_.accept();
-
WorkerProcess wp = new WorkerProcess(client);
-
executorService_.execute(wp);
-
} catch (TTransportException ttx) {
-
}
-
}
* TNonblockingServer – 采用NIO的模式, 借助Channel/Selector機制, 采用IO事件模型來處理。
-
private void select() {
-
try {
-
selector.select(); // wait for io events.
-
// process the io events we received
-
Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
-
while (!stopped_ && selectedKeys.hasNext()) {
-
SelectionKey key = selectedKeys.next();
-
selectedKeys.remove();
-
if (key.isAcceptable()) {
-
handleAccept(); // deal with accept
-
} else if (key.isReadable()) {
-
handleRead(key); // deal with reads
-
} else if (key.isWritable()) {
-
handleWrite(key); // deal with writes
-
}
-
}
-
} catch (IOException e) {
-
}
-
}
*THsHaServer - 半同步半異步
鑒於TNonblockingServer的缺點, THsHa引入了線程池去處理, 其模型把讀寫任務放到線程池去處理。HsHa是: Half-sync/Half-async的處理模式, Half-aysnc是在處理IO事件上(accept/read/write io), Half-sync用於handler對rpc的同步處理上.
*TThreadedSelectorServer- 多線程服務器端使用非堵塞式I/O,是對以上NonblockingServer的擴充, 其分離了Accept和Read/Write的Selector線程, 同時引入Worker工作線程池. 它也是種Half-sync/Half-async的服務模型,也是最成熟,也是被業界所推崇的RPC服務模型。

MainReactor就是Accept線程, 用於監聽客戶端連接, SubReactor采用IO事件線程(多個), 主要負責對所有客戶端的IO讀寫事件進行處理. 而Worker工作線程主要用於處理每個rpc請求的handler回調處理(這部分是同步的)。
- Java簡單實例
namespace java cn.slimsmart.thrift.demo.helloworld service HelloWorld{ string sayHello(1:string username) } 2.生成java接口文件
-
/**
-
* Autogenerated by Thrift Compiler (0.9.2)
-
*
-
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-
* @generated
-
*/
-
package cn.slimsmart.thrift.demo.helloworld;
-
-
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;
-
-
/**
-
* 通過HelloWord.thrift 生成的接口類
-
*/
-
-
-
public class HelloWorld {
-
-
//同步接口
-
public interface Iface {
-
public String sayHello(String username) throws org.apache.thrift.TException;
-
}
-
-
//異步接口
-
public interface AsyncIface {
-
public void sayHello(String username, 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 username) throws org.apache.thrift.TException
-
{
-
send_sayHello(username);
-
return recv_sayHello();
-
}
-
-
public void send_sayHello(String username) throws org.apache.thrift.TException
-
{
-
sayHello_args args = new sayHello_args();
-
args.setUsername(username);
-
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 username, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
-
checkReady();
-
sayHello_call method_call = new sayHello_call(username, 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 username;
-
public sayHello_call(String username, 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.username = username;
-
}
-
-
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.setUsername(username);
-
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 {
-
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.username);
-
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;
-
{
-
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.username,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 USERNAME_FIELD_DESC = new org.apache.thrift.protocol.TField("username", 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 username; // 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 {
-
USERNAME(( short)1, "username");
-
-
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: // USERNAME
-
return USERNAME;
-
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.USERNAME, new org.apache.thrift.meta_data.FieldMetaData("username", 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 username)
-
{
-
this();
-
this.username = username;
-
}
-
-
/**
-
* Performs a deep copy on <i>other</i>.
-
*/
-
public sayHello_args(sayHello_args other) {
-
if (other.isSetUsername()) {
-
this.username = other.username;
-
}
-
}
-
-
public sayHello_args deepCopy() {
-
return new sayHello_args(this);
-
}
-
-
-
public void clear() {
-
this.username = null;
-
}
-
-
public String getUsername() {
-
return this.username;
-
}
-
-
public sayHello_args setUsername(String username) {
-
this.username = username;
-
return this;
-
}
-
-
public void unsetUsername() {
-
this.username = null;
-
}
-
-
/** Returns true if field username is set (has been assigned a value) and false otherwise */
-
public boolean isSetUsername() {
-
return this.username != null;
-
}
-
-
public void setUsernameIsSet(boolean value) {
-
if (!value) {
-
this.username = null;
-
}
-
}
-
-
public void setFieldValue(_Fields field, Object value) {
-
switch (field) {
-
case USERNAME:
-
if (value == null) {
-
unsetUsername();
-
} else {
-
setUsername((String)value);
-
}
-
break;
-
-
}
-
}
-
-
public Object getFieldValue(_Fields field) {
-
switch (field) {
-
case USERNAME:
-
return getUsername();
-
-
}
-
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 USERNAME:
-
return isSetUsername();
-
}
-
throw new IllegalStateException();
-
}
-
-
-
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_username = true && this.isSetUsername();
-
boolean that_present_username = true && that.isSetUsername();
-
if (this_present_username || that_present_username) {
-
if (!(this_present_username && that_present_username))
-
return false;
-
if (!this.username.equals(that.username))
-
return false;
-
}
-
-
return true;
-
}
-
-
-
public int hashCode() {
-
List<Object> list = new ArrayList<Object>();
-
-
boolean present_username = true && (isSetUsername());
-
list.add(present_username);
-
if (present_username)
-
list.add(username);
-
-
return list.hashCode();
-
}
-
-
-
public int compareTo(sayHello_args other) {
-
if (!getClass().equals(other.getClass())) {
-
return getClass().getName().compareTo(other.getClass().getName());
-
}
-
-
int lastComparison = 0;
-
-
lastComparison = Boolean.valueOf(isSetUsername()).compareTo(other.isSetUsername());
-
if (lastComparison != 0) {
-
return lastComparison;
-
}
-
if (isSetUsername()) {
-
lastComparison = org.apache.thrift.TBaseHelper.compareTo( this.username, other.username);
-
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);
-
}
-
-
-
public String toString() {
-
StringBuilder sb = new StringBuilder("sayHello_args(");
-
sb.append( "username:");
-
if (this.username == null) {
-
sb.append( "null");
-
} else {
-
sb.append( this.username);
-
}
-
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: // USERNAME
-
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
-
struct.username = iprot.readString();
-
struct.setUsernameIsSet( 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.username != null) {
-
oprot.writeFieldBegin(USERNAME_FIELD_DESC);
-
oprot.writeString(struct.username);
-
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> {
-
-
-
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.isSetUsername()) {
-
optionals.set( 0);
-
}
-
oprot.writeBitSet(optionals, 1);
-
if (struct.isSetUsername()) {
-
oprot.writeString(struct.username);
-
}
-
}
-
-
-
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.username = iprot.readString();
-
struct.setUsernameIsSet( 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);
-
}
-
-
-
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();
-
}
-
-
-
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;
-
}
-
-
-
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(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);
-
}
-
-
-
public String toString() {
-
StringBuilder sb = new StringBuilder("sayHello_result(");
-
sb.append( "success:");
-
if (this.success == null) {
-
sb.append( "null");
-
} else {
-
sb.append( this.success);
-
}
-
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> {
-
-
-
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);
-
}
-
}
-
-
-
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);
-
}
-
}
-
}
-
-
}
-
-
}
-
<dependency>
-
<groupId>org.apache.thrift</groupId>
-
<artifactId>libthrift</artifactId>
-
<version>0.9.2</version>
-
</dependency>
-
<dependency>
-
<groupId>org.slf4j</groupId>
-
<artifactId>slf4j-log4j12</artifactId>
-
<version>1.5.8</version>
-
</dependency>
-
package cn.slimsmart.thrift.demo.helloworld;
-
-
import org.apache.thrift.TException;
-
-
/**
-
* HelloWord 接口實現類
-
*
-
*/
-
public class HelloWorldImpl implements HelloWorld.Iface{
-
-
public String sayHello(String username) throws TException {
-
return "hello world, "+username;
-
}
-
}
-
package cn.slimsmart.thrift.demo.helloworld;
-
-
import org.apache.thrift.TException;
-
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;
-
-
/**
-
* 注冊服務端 阻塞式、單線程
-
* 簡單的單線程服務模型 TSimpleServer
-
*/
-
public class HelloTSimpleServer {
-
// 注冊端口
-
public static final int SERVER_PORT = 8080;
-
-
public static void main(String[] args) throws TException {
-
//設置處理器
-
TProcessor tprocessor = new HelloWorld.Processor<HelloWorld.Iface>(new HelloWorldImpl());
-
// 簡單的單線程服務模型,阻塞IO
-
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);
-
System.out.println( "HelloServer start....");
-
server.serve(); // 啟動服務
-
}
-
}
-
package cn.slimsmart.thrift.demo.helloworld;
-
-
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;
-
-
/**
-
* 客戶端調用HelloTSimpleServer,HelloTThreadPoolServer
-
* 阻塞
-
*/
-
public class HelloClient {
-
public static final String SERVER_IP = "127.0.0.1";
-
public static final int SERVER_PORT = 8080;
-
public static final int TIMEOUT = 30000;
-
-
public static void main(String[] args) throws TException {
-
// 設置傳輸通道
-
TTransport transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
-
// 協議要和服務端一致
-
//使用二進制協議
-
TProtocol protocol = new TBinaryProtocol(transport);
-
//創建Client
-
HelloWorld.Client client = new HelloWorld.Client(protocol);
-
transport.open();
-
String result = client.sayHello( "jack");
-
System.out.println( "result : " + result);
-
//關閉資源
-
transport.close();
-
}
-
}<strong>
-
</strong>
