先声明:此swift不是Apple公司的那个swift开发语言,而是facebook的另一个开源项目。

facebook的thrift IDL文件,如果默认用thrift -gen java生成java代码,代码十分冗长,大家可以先感受一下。
一、IDL文件

service HelloService{
string ping()
}

二、thrift命令生成的HelloService.java

/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
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-03-22")
public class HelloService { public interface Iface { public String ping() throws org.apache.thrift.TException; } public interface AsyncIface { public void ping(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 ping() throws org.apache.thrift.TException
{
send_ping();
return recv_ping();
} public void send_ping() throws org.apache.thrift.TException
{
ping_args args = new ping_args();
sendBase("ping", args);
} public String recv_ping() throws org.apache.thrift.TException
{
ping_result result = new ping_result();
receiveBase(result, "ping");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "ping 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 ping(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
checkReady();
ping_call method_call = new ping_call(resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
} public static class ping_call extends org.apache.thrift.async.TAsyncMethodCall {
public ping_call(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);
} public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("ping", org.apache.thrift.protocol.TMessageType.CALL, 0));
ping_args args = new ping_args();
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_ping();
}
} } 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("ping", new ping());
return processMap;
} public static class ping<I extends Iface> extends org.apache.thrift.ProcessFunction<I, ping_args> {
public ping() {
super("ping");
} public ping_args getEmptyArgsInstance() {
return new ping_args();
} protected boolean isOneway() {
return false;
} public ping_result getResult(I iface, ping_args args) throws org.apache.thrift.TException {
ping_result result = new ping_result();
result.success = iface.ping();
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("ping", new ping());
return processMap;
} public static class ping<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, ping_args, String> {
public ping() {
super("ping");
} public ping_args getEmptyArgsInstance() {
return new ping_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) {
ping_result result = new ping_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;
ping_result result = new ping_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, ping_args args, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws TException {
iface.ping(resultHandler);
}
} } public static class ping_args implements org.apache.thrift.TBase<ping_args, ping_args._Fields>, java.io.Serializable, Cloneable, Comparable<ping_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ping_args"); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new ping_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new ping_argsTupleSchemeFactory());
} /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
; 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) {
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;
}
}
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);
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ping_args.class, metaDataMap);
} public ping_args() {
} /**
* Performs a deep copy on <i>other</i>.
*/
public ping_args(ping_args other) {
} public ping_args deepCopy() {
return new ping_args(this);
} @Override
public void clear() {
} public void setFieldValue(_Fields field, Object value) {
switch (field) {
}
} public Object getFieldValue(_Fields field) {
switch (field) {
}
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) {
}
throw new IllegalStateException();
} @Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof ping_args)
return this.equals((ping_args)that);
return false;
} public boolean equals(ping_args that) {
if (that == null)
return false; return true;
} @Override
public int hashCode() {
List<Object> list = new ArrayList<Object>(); return list.hashCode();
} @Override
public int compareTo(ping_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
} int lastComparison = 0; 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("ping_args(");
boolean first = true; 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 ping_argsStandardSchemeFactory implements SchemeFactory {
public ping_argsStandardScheme getScheme() {
return new ping_argsStandardScheme();
}
} private static class ping_argsStandardScheme extends StandardScheme<ping_args> { public void read(org.apache.thrift.protocol.TProtocol iprot, ping_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) {
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, ping_args struct) throws org.apache.thrift.TException {
struct.validate(); oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldStop();
oprot.writeStructEnd();
} } private static class ping_argsTupleSchemeFactory implements SchemeFactory {
public ping_argsTupleScheme getScheme() {
return new ping_argsTupleScheme();
}
} private static class ping_argsTupleScheme extends TupleScheme<ping_args> { @Override
public void write(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
} @Override
public void read(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
}
} } public static class ping_result implements org.apache.thrift.TBase<ping_result, ping_result._Fields>, java.io.Serializable, Cloneable, Comparable<ping_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ping_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 ping_resultStandardSchemeFactory());
schemes.put(TupleScheme.class, new ping_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(ping_result.class, metaDataMap);
} public ping_result() {
} public ping_result(
String success)
{
this();
this.success = success;
} /**
* Performs a deep copy on <i>other</i>.
*/
public ping_result(ping_result other) {
if (other.isSetSuccess()) {
this.success = other.success;
}
} public ping_result deepCopy() {
return new ping_result(this);
} @Override
public void clear() {
this.success = null;
} public String getSuccess() {
return this.success;
} public ping_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 ping_result)
return this.equals((ping_result)that);
return false;
} public boolean equals(ping_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(ping_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("ping_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 ping_resultStandardSchemeFactory implements SchemeFactory {
public ping_resultStandardScheme getScheme() {
return new ping_resultStandardScheme();
}
} private static class ping_resultStandardScheme extends StandardScheme<ping_result> { public void read(org.apache.thrift.protocol.TProtocol iprot, ping_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, ping_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 ping_resultTupleSchemeFactory implements SchemeFactory {
public ping_resultTupleScheme getScheme() {
return new ping_resultTupleScheme();
}
} private static class ping_resultTupleScheme extends TupleScheme<ping_result> { @Override
public void write(org.apache.thrift.protocol.TProtocol prot, ping_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, ping_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);
}
}
} } }

对于有代码洁癖的人来说,尝试阅读这一巨型java类是很别扭的。swift子项目正好解决了这个问题,它可以通过注解极大简化最终生成的thrift 服务java代码,大家可以对比一下:

三、swift生成的HelloService代码

package yjmyzz.cnblogs.com.thrift.swift;

import com.facebook.swift.service.ThriftMethod;
import com.facebook.swift.service.ThriftService;
import com.google.common.util.concurrent.ListenableFuture; @ThriftService("HelloService")
public interface HelloService
{
@ThriftService("HelloService")
public interface Async
{
@ThriftMethod(value = "ping")
ListenableFuture<String> ping();
}
@ThriftMethod(value = "ping")
String ping() throws org.apache.thrift.TException;
}

上面这段代码,可以用maven-plugin生成:

四、swift-maven-plugin 配置

 <plugins>
<plugin>
<groupId>com.facebook.mojo</groupId>
<artifactId>swift-maven-plugin</artifactId>
<version>${swift-version}</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<skip>false</skip>
<idlFiles>
<directory>${project.basedir}/src/main/thrift/</directory>
<includes>
<include>**/*.thrift</include>
</includes>
<!--<excludes>-->
<!--<exclude>**/other.thrift</exclude>-->
<!--</excludes>-->
</idlFiles>
<defaultPackage>${project.groupId}.thrift.swift</defaultPackage>
<outputFolder>${project.basedir}/src/main/java/</outputFolder>
</configuration>
</plugin>
</plugins>

五、服务端代码示例

为了方便,先封装一个服务启动的辅助类

package yjmyzz.cnblogs.com.thrift.server;

import com.facebook.nifty.core.NettyServerConfig;
import com.facebook.nifty.core.ThriftServerDef;
import com.facebook.swift.codec.ThriftCodecManager;
import com.facebook.swift.service.ThriftEventHandler;
import com.facebook.swift.service.ThriftServer;
import com.facebook.swift.service.ThriftServiceProcessor;
import com.google.common.collect.ImmutableList;
import org.junit.Assert;
import yjmyzz.cnblogs.com.thrift.service.HelloServiceImpl; import java.util.concurrent.ExecutorService; import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.Executors.newFixedThreadPool; /**
* Created by yangjunming on 3/22/16.
* author: yangjunming@huijiame.com
*/
public class ServerCreator {
private ExecutorService taskWorkerExecutor;
private ThriftServer server;
private ExecutorService bossExecutor;
private ExecutorService ioWorkerExecutor; public ThriftServer getServer() {
return server;
} public ServerCreator invoke() {
ThriftServiceProcessor processor = new ThriftServiceProcessor(
new ThriftCodecManager(),
ImmutableList.<ThriftEventHandler>of(),
new HelloServiceImpl()
); taskWorkerExecutor = newFixedThreadPool(1); ThriftServerDef serverDef = ThriftServerDef.newBuilder()
.listen(12345)
.withProcessor(processor)
.using(taskWorkerExecutor)
.build(); bossExecutor = newCachedThreadPool();
ioWorkerExecutor = newCachedThreadPool(); NettyServerConfig serverConfig = NettyServerConfig.newBuilder()
.setBossThreadExecutor(bossExecutor)
.setWorkerThreadExecutor(ioWorkerExecutor)
.build(); server = new ThriftServer(serverConfig, serverDef);
return this;
} public void checkExecutorsTerminated() {
Assert.assertTrue(bossExecutor.isTerminated());
Assert.assertTrue(ioWorkerExecutor.isTerminated());
Assert.assertTrue(taskWorkerExecutor.isTerminated());
} public void stop() {
server.close();
}
}

然后就可以直接用了:

package yjmyzz.cnblogs.com.thrift.server;

import com.facebook.swift.service.ThriftServer;

/**
* Created by yangjunming on 3/22/16.
* author: yangjunming@huijiame.com
*/
public class ThriftServerDemo { public static void main(String[] args) { ServerCreator serverCreator = new ServerCreator().invoke();
ThriftServer server = serverCreator.getServer(); server.start();
System.out.println("服务已启动!"); //serverCreator.stop();
//serverCreator.checkExecutorsTerminated(); } }

六、客户端代码

package yjmyzz.cnblogs.com.thrift.client;

import com.facebook.nifty.client.FramedClientConnector;
import com.facebook.swift.service.ThriftClientManager;
import org.apache.thrift.TException;
import yjmyzz.cnblogs.com.thrift.swift.HelloService;
import java.util.concurrent.ExecutionException;
import static com.google.common.net.HostAndPort.fromParts; /**
* Created by yangjunming on 3/22/16.
* author: yangjunming@huijiame.com
*/
public class ThriftClientDemo { public static void main(String[] args) throws ExecutionException, InterruptedException, TException { ThriftClientManager clientManager = new ThriftClientManager();
HelloService helloService = clientManager.createClient(
new FramedClientConnector(fromParts("localhost", 12345)),
HelloService.class).get();
System.out.println(helloService.ping()); int max = 100000;
Long start = System.currentTimeMillis();
for (int i = 0; i < max; i++) {
helloService.ping();
}
Long end = System.currentTimeMillis();
Long elapse = end - start;
int perform = Double.valueOf(max / (elapse / 1000d)).intValue(); System.out.print("thrift " + max + " 次RPC调用,耗时:" + elapse + "毫秒,平均" + perform + "次/秒"); }
}

上面的代码,server/client是基于netty实现的,在我mac pro上的结果大概1秒8k+次, 相对thrift原生成的实现,性能只有70%上下。

thrift:swift项目笔记的更多相关文章

  1. Swift学习笔记(一)搭配环境以及代码运行成功

    原文:Swift学习笔记(一)搭配环境以及代码运行成功 1.Swift是啥? 百度去!度娘告诉你它是苹果最新推出的编程语言,比c,c++,objc要高效简单.能够开发ios,mac相关的app哦!是苹 ...

  2. 记录:swift学习笔记1-2

    swift还在不断的更新做细微的调整,都说早起的鸟儿有虫吃,那么我们早点出发吧,趁着国内绝大多数的coder们还没有开始大范围普遍应用. 网上有些大神说:swift很简单!我不同意这个观点,假如你用h ...

  3. Swift开发笔记

    Swift开发笔记(一) 刚开始接触XCode时,整个操作逻辑与Android Studio.Visual Studio等是完全不同的,因此本文围绕IOS中控件的设置.事件的注册来简单的了解IOS开发 ...

  4. 【swift学习笔记】二.页面转跳数据回传

    上一篇我们介绍了页面转跳:[swift学习笔记]一.页面转跳的条件判断和传值 这一篇说一下如何把数据回传回父页面,如下图所示,这个例子很简单,只是把传过去的数据加上了"回传"两个字 ...

  5. 在Swift项目中使用cocoaPods导入第三方OC库

    首先保证你的项目是基于cocoaPods的,并且是通过XX.xcworkspace打开的.cocoaPods安装教程(Xcode6以上) 下面就第三方库MBProgressHUD来讲解如何在Swift ...

  6. 《BI项目笔记》——微软BI项目笔记连载

    本系列文章主要是结合实际项目,加上自己的总结,整理出来的一系列项目笔记,涉及微软SQL Server2008中商务智能开发中的SSAS.SSIS模块:  准备工作: <BI项目笔记>基于雪 ...

  7. swift项目中使用OC/C的方法

    假如有个OC类OCViewController : UIViewController类里有两个方法 //swift调用oc或c的混编是比较常用的,反过来的调用很少.这里只写了swift调用oc和c的方 ...

  8. 自学 iOS – 三十天三十个 Swift 项目

    自学 iOS – 三十天三十个 Swift 项目 github源码地址:https://github.com/allenwong/30DaysofSwift

  9. Swift项目兼容Objective-C问题汇总

    Swift项目兼容Objective-C问题汇总 转载自 http://www.cocoachina.com/swift/20150608/12025.html 本文是投稿文章,作者:一叶(博客)欢迎 ...

随机推荐

  1. 【Java心得总结一】Java基本类型和包装类型解析

    说到数据类型这个问题是一个基本的不能再基本的问题,我们当初编程入门第一课一般就是讲数据类型,而今天我想记录的是一个在Java中容易忽略的问题,即基本类型和包装类型. 一.基本类型出现的原因 我们都知道 ...

  2. Vertica 业务用户指定资源池加载数据

    之前在"Vertica 安装,建库,新建测试用户并授予权限,建表,入库"这篇文章也简单介绍过入库部分的内容. 但之前测试用例若用于生产环境有明显的局限性: 1.是用dbadmin管 ...

  3. 【目录】Zookeeper目录

    Zookeeper的目录整理如下 1. [分布式]分布式架构 2. [分布式]一致性协议 3. [分布式]Chubby与Paxos 4. [分布式]Zookeeper与Paxos 5. [分布式]Zo ...

  4. Elasticsearch —— bulk批量导入数据

    在使用Elasticsearch的时候,一定会遇到这种场景--希望批量的导入数据,而不是一条一条的手动导入.那么此时,就一定会需要bulk命令! 更多内容参考我整理的Elk教程 bulk批量导入 批量 ...

  5. ASP.NET Core 静态文件及JS包管理器(npm, Bower)的使用

    在 ASP.NET Core 中添加静态文件 虽然ASP.NET主要大都做着后端的事情,但前端的一些静态文件也是很重要的.在ASP.NET Core中要启用静态文件,需要Microsoft.AspNe ...

  6. 【手记】为windows2008建个睡眠快捷方式

    ----------------201607041343更新---------------- 在另一台电脑上SetSystemPowerState又不好使了,执行了根本没反应.又回头来试SetSusp ...

  7. 使用 SSH上传安装tomcat

    开发步骤: 1.在soft文件夹下上传tomcat 2.[root@localhost soft]# tar  -zxvf apache-tomcat-7.0.61.tar.gz    //解压安装 ...

  8. spring源码:IOC(li)

    一.BeanDefinition BeanDefinition是配置文件<bean>元素标签在容器中内部表示形式.创建最终的BeanDefinition主要包括两个步骤: 1)利用Bean ...

  9. Java集合-Python数据结构比较

    Java list与Python list相比较 Java List:有序的,可重复的.(有序指的是集合中对象的顺序与添加顺序相同) Python list(列表)是有序的,可变的. Java Lis ...

  10. ATM-PROGRAM 关于Proprties的问题

    public static void turnMoney(String ToAccNo, int money){ d = new Date(); dateStr = noteDate.format(d ...