JAVA RPC Thrift基操实现与微服务间调用

一、Thrift 基操实现

1.1 thrift文件

namespace java com.zn.opit.thrift.helloworldservice HelloWorldService {string sayHello(1:string username)
}

1.2 执行命令生成Java文件

thrift -r --gen java helloworld.thrift

生成代码HelloWorldService接口如下

/*** Autogenerated by Thrift Compiler (0.11.0)** DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING*  @generated*/
package com.zn.opit.thrift.helloworld;@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.11.0)", date = "2023-10-29")
public class HelloWorldService {public interface Iface {public java.lang.String sayHello(java.lang.String username) throws org.apache.thrift.TException;}public interface AsyncIface {public void sayHello(java.lang.String username, org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler) throws org.apache.thrift.TException;}public static class Client extends org.apache.thrift.TServiceClient implements Iface {public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {public Factory() {}public Client getClient(org.apache.thrift.protocol.TProtocol prot) {return new Client(prot);}public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {return new Client(iprot, oprot);}}public Client(org.apache.thrift.protocol.TProtocol prot){super(prot, prot);}public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {super(iprot, oprot);}public java.lang.String sayHello(java.lang.String username) throws org.apache.thrift.TException{send_sayHello(username);return recv_sayHello();}public void send_sayHello(java.lang.String username) throws org.apache.thrift.TException{sayHello_args args = new sayHello_args();args.setUsername(username);sendBase("sayHello", args);}public java.lang.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(java.lang.String username, org.apache.thrift.async.AsyncMethodCallback<java.lang.String> 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<java.lang.String> {private java.lang.String username;public sayHello_call(java.lang.String username, org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {super(client, protocolFactory, transport, resultHandler, false);this.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 java.lang.String getResult() throws org.apache.thrift.TException {if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {throw new java.lang.IllegalStateException("Method call not finished!");}org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);return (new Client(prot)).recv_sayHello();}}}public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName());public Processor(I iface) {super(iface, getProcessMap(new java.util.HashMap<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));}protected Processor(I iface, java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {super(iface, getProcessMap(processMap));}private static <I extends Iface> java.util.Map<java.lang.String,  org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends  org.apache.thrift.TBase>> processMap) {processMap.put("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;}@Overrideprotected boolean handleRuntimeExceptions() {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 org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName());public AsyncProcessor(I iface) {super(iface, getProcessMap(new java.util.HashMap<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));}protected AsyncProcessor(I iface, java.util.Map<java.lang.String,  org.apache.thrift.AsyncProcessFunction<I, ? extends  org.apache.thrift.TBase, ?>> processMap) {super(iface, getProcessMap(processMap));}private static <I extends AsyncIface> java.util.Map<java.lang.String,  org.apache.thrift.AsyncProcessFunction<I, ? extends  org.apache.thrift.TBase,?>> getProcessMap(java.util.Map<java.lang.String,  org.apache.thrift.AsyncProcessFunction<I, ? extends  org.apache.thrift.TBase, ?>> processMap) {processMap.put("sayHello", new sayHello());return processMap;}public static class sayHello<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, sayHello_args, java.lang.String> {public sayHello() {super("sayHello");}public sayHello_args getEmptyArgsInstance() {return new sayHello_args();}public org.apache.thrift.async.AsyncMethodCallback<java.lang.String> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {final org.apache.thrift.AsyncProcessFunction fcall = this;return new org.apache.thrift.async.AsyncMethodCallback<java.lang.String>() { public void onComplete(java.lang.String o) {sayHello_result result = new sayHello_result();result.success = o;try {fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);} catch (org.apache.thrift.transport.TTransportException e) {_LOGGER.error("TTransportException writing to internal frame buffer", e);fb.close();} catch (java.lang.Exception e) {_LOGGER.error("Exception writing to internal frame buffer", e);onError(e);}}public void onError(java.lang.Exception e) {byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;org.apache.thrift.TSerializable msg;sayHello_result result = new sayHello_result();if (e instanceof org.apache.thrift.transport.TTransportException) {_LOGGER.error("TTransportException inside handler", e);fb.close();return;} else if (e instanceof org.apache.thrift.TApplicationException) {_LOGGER.error("TApplicationException inside handler", e);msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;msg = (org.apache.thrift.TApplicationException)e;} else {_LOGGER.error("Exception inside handler", e);msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());}try {fcall.sendResponse(fb,msg,msgType,seqid);} catch (java.lang.Exception ex) {_LOGGER.error("Exception writing to internal frame buffer", ex);fb.close();}}};}protected boolean isOneway() {return false;}public void start(I iface, sayHello_args args, org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler) throws org.apache.thrift.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 org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHello_argsStandardSchemeFactory();private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHello_argsTupleSchemeFactory();public java.lang.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 java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();static {for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {byName.put(field.getFieldName(), field);}}/*** Find the _Fields constant that matches fieldId, or null if its not found.*/public static _Fields findByThriftId(int fieldId) {switch(fieldId) {case 1: // USERNAMEreturn 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 java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");return fields;}/*** Find the _Fields constant that matches name, or null if its not found.*/public static _Fields findByName(java.lang.String name) {return byName.get(name);}private final short _thriftId;private final java.lang.String _fieldName;_Fields(short thriftId, java.lang.String fieldName) {_thriftId = thriftId;_fieldName = fieldName;}public short getThriftFieldId() {return _thriftId;}public java.lang.String getFieldName() {return _fieldName;}}// isset id assignmentspublic static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;static {java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);tmpMap.put(_Fields.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 = java.util.Collections.unmodifiableMap(tmpMap);org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_args.class, metaDataMap);}public sayHello_args() {}public sayHello_args(java.lang.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);}@Overridepublic void clear() {this.username = null;}public java.lang.String getUsername() {return this.username;}public sayHello_args setUsername(java.lang.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, java.lang.Object value) {switch (field) {case USERNAME:if (value == null) {unsetUsername();} else {setUsername((java.lang.String)value);}break;}}public java.lang.Object getFieldValue(_Fields field) {switch (field) {case USERNAME:return getUsername();}throw new java.lang.IllegalStateException();}/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */public boolean isSet(_Fields field) {if (field == null) {throw new java.lang.IllegalArgumentException();}switch (field) {case USERNAME:return isSetUsername();}throw new java.lang.IllegalStateException();}@Overridepublic boolean equals(java.lang.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;if (this == that)return true;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;}@Overridepublic int hashCode() {int hashCode = 1;hashCode = hashCode * 8191 + ((isSetUsername()) ? 131071 : 524287);if (isSetUsername())hashCode = hashCode * 8191 + username.hashCode();return hashCode;}@Overridepublic int compareTo(sayHello_args other) {if (!getClass().equals(other.getClass())) {return getClass().getName().compareTo(other.getClass().getName());}int lastComparison = 0;lastComparison = java.lang.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 {scheme(iprot).read(iprot, this);}public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {scheme(oprot).write(oprot, this);}@Overridepublic java.lang.String toString() {java.lang.StringBuilder sb = new java.lang.StringBuilder("sayHello_args(");boolean first = true;sb.append("username:");if (this.username == null) {sb.append("null");} else {sb.append(this.username);}first = false;sb.append(")");return sb.toString();}public void validate() throws org.apache.thrift.TException {// check for required fields// check for sub-struct validity}private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {try {write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));} catch (org.apache.thrift.TException te) {throw new java.io.IOException(te);}}private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {try {read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));} catch (org.apache.thrift.TException te) {throw new java.io.IOException(te);}}private static class sayHello_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {public sayHello_argsStandardScheme getScheme() {return new sayHello_argsStandardScheme();}}private static class sayHello_argsStandardScheme extends org.apache.thrift.scheme.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: // USERNAMEif (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 methodstruct.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 org.apache.thrift.scheme.SchemeFactory {public sayHello_argsTupleScheme getScheme() {return new sayHello_argsTupleScheme();}}private static class sayHello_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme<sayHello_args> {@Overridepublic void write(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException {org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;java.util.BitSet optionals = new java.util.BitSet();if (struct.isSetUsername()) {optionals.set(0);}oprot.writeBitSet(optionals, 1);if (struct.isSetUsername()) {oprot.writeString(struct.username);}}@Overridepublic void read(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException {org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;java.util.BitSet incoming = iprot.readBitSet(1);if (incoming.get(0)) {struct.username = iprot.readString();struct.setUsernameIsSet(true);}}}private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();}}public static class 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 org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHello_resultStandardSchemeFactory();private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHello_resultTupleSchemeFactory();public java.lang.String success; // required/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */public enum _Fields implements org.apache.thrift.TFieldIdEnum {SUCCESS((short)0, "success");private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();static {for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {byName.put(field.getFieldName(), field);}}/*** Find the _Fields constant that matches fieldId, or null if its not found.*/public static _Fields findByThriftId(int fieldId) {switch(fieldId) {case 0: // SUCCESSreturn SUCCESS;default:return null;}}/*** Find the _Fields constant that matches fieldId, throwing an exception* if it is not found.*/public static _Fields findByThriftIdOrThrow(int fieldId) {_Fields fields = findByThriftId(fieldId);if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");return fields;}/*** Find the _Fields constant that matches name, or null if its not found.*/public static _Fields findByName(java.lang.String name) {return byName.get(name);}private final short _thriftId;private final java.lang.String _fieldName;_Fields(short thriftId, java.lang.String fieldName) {_thriftId = thriftId;_fieldName = fieldName;}public short getThriftFieldId() {return _thriftId;}public java.lang.String getFieldName() {return _fieldName;}}// isset id assignmentspublic static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;static {java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_result.class, metaDataMap);}public sayHello_result() {}public sayHello_result(java.lang.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);}@Overridepublic void clear() {this.success = null;}public java.lang.String getSuccess() {return this.success;}public sayHello_result setSuccess(java.lang.String success) {this.success = success;return this;}public void unsetSuccess() {this.success = null;}/** Returns true if field success is set (has been assigned a value) and false otherwise */public boolean isSetSuccess() {return this.success != null;}public void setSuccessIsSet(boolean value) {if (!value) {this.success = null;}}public void setFieldValue(_Fields field, java.lang.Object value) {switch (field) {case SUCCESS:if (value == null) {unsetSuccess();} else {setSuccess((java.lang.String)value);}break;}}public java.lang.Object getFieldValue(_Fields field) {switch (field) {case SUCCESS:return getSuccess();}throw new java.lang.IllegalStateException();}/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */public boolean isSet(_Fields field) {if (field == null) {throw new java.lang.IllegalArgumentException();}switch (field) {case SUCCESS:return isSetSuccess();}throw new java.lang.IllegalStateException();}@Overridepublic boolean equals(java.lang.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;if (this == that)return true;boolean this_present_success = true && this.isSetSuccess();boolean that_present_success = true && that.isSetSuccess();if (this_present_success || that_present_success) {if (!(this_present_success && that_present_success))return false;if (!this.success.equals(that.success))return false;}return true;}@Overridepublic int hashCode() {int hashCode = 1;hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287);if (isSetSuccess())hashCode = hashCode * 8191 + success.hashCode();return hashCode;}@Overridepublic int compareTo(sayHello_result other) {if (!getClass().equals(other.getClass())) {return getClass().getName().compareTo(other.getClass().getName());}int lastComparison = 0;lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());if (lastComparison != 0) {return lastComparison;}if (isSetSuccess()) {lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);if (lastComparison != 0) {return lastComparison;}}return 0;}public _Fields fieldForId(int fieldId) {return _Fields.findByThriftId(fieldId);}public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {scheme(iprot).read(iprot, this);}public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {scheme(oprot).write(oprot, this);}@Overridepublic java.lang.String toString() {java.lang.StringBuilder sb = new java.lang.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, java.lang.ClassNotFoundException {try {read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));} catch (org.apache.thrift.TException te) {throw new java.io.IOException(te);}}private static class sayHello_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {public sayHello_resultStandardScheme getScheme() {return new sayHello_resultStandardScheme();}}private static class sayHello_resultStandardScheme extends org.apache.thrift.scheme.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: // SUCCESSif (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 methodstruct.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 org.apache.thrift.scheme.SchemeFactory {public sayHello_resultTupleScheme getScheme() {return new sayHello_resultTupleScheme();}}private static class sayHello_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme<sayHello_result> {@Overridepublic void write(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException {org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;java.util.BitSet optionals = new java.util.BitSet();if (struct.isSetSuccess()) {optionals.set(0);}oprot.writeBitSet(optionals, 1);if (struct.isSetSuccess()) {oprot.writeString(struct.success);}}@Overridepublic void read(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException {org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;java.util.BitSet incoming = iprot.readBitSet(1);if (incoming.get(0)) {struct.success = iprot.readString();struct.setSuccessIsSet(true);}}}private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();}}}

1.3 实现HelloWorldService

public class HelloWordServiceImpl implements HelloWorldService.Iface {@Overridepublic String sayHello(String username) throws TException {return "hello, " + username;}
}

1.4 服务端

@Slf4j
public class ThriftServer {public static final int SERVER_PORT = 8010;public static void main(String[] args) throws Exception {log.info("服务端开启....");// 启动服务new TSimpleServer(new TServer.Args(new TServerSocket(new ServerSocket(SERVER_PORT))).processor(new HelloWorldService.Processor<HelloWorldService.Iface>(new HelloWordServiceImpl())).protocolFactory(new TBinaryProtocol.Factory())).serve();}
}

1.5 客户端

@Slf4j
public class ThriftClient {// 服务端IP地址public static final String SERVER_IP = "127.0.0.1";// 服务端端口号public static final int SERVER_PORT = 8010;public static void main(String[] args) throws Exception {log.info("客户端启动....");try (TTransport transport = new TSocket(SERVER_IP, SERVER_PORT)) {TProtocol protocol = new TBinaryProtocol(transport);HelloWorldService.Client client = new HelloWorldService.Client(protocol);transport.open();System.out.println("result = [remote: " + client.sayHello("wangxiaohu") + "]");} catch (Exception e) {log.error("客户端启动失败", e);}}
}

1.6 启动服务端、客户端进行测试

  • 先启动服务端
  • 在启动客户端

测试

二、微服务间相互调用

2.1 通过thrift生成HelloWorldService

往前调转 1.2 执行命令生成Java文件

2.2 thrift客户端代理

/*** Thrift客户端代理*/
@SuppressWarnings({"unchecked" })
public class ThriftClientProxy {// 服务端端口号public static final int SERVER_PORT = 50000;public static <T> T getRemoteProxyObj(final Class<?> serviceInterface, String host) {return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(),new Class<?>[]{serviceInterface},(proxy, method, args) -> {TTransport transport = new TSocket(host, SERVER_PORT);TProtocol protocol = new TBinaryProtocol(transport);Class<?>[] argsClass = new Class[]{TProtocol.class};Constructor<?> cons = Class.forName(serviceInterface.getName().replace("Iface", "Client")).getConstructor(argsClass);T client = (T) cons.newInstance(protocol);transport.open();return method.invoke(client, args);});}
}

2.3 Thrift服务端代理

/*** Thrift服务端代理*/
public class ThriftServerProxy {private final Logger logger = LoggerFactory.getLogger(getClass());private static final int THRIFT_SERVER_PORT = 50000;// 端口private String serviceInterface;// 实现类接口private Object serviceImplObject;// 实现类@SuppressWarnings({ "unchecked", "rawtypes" })public void start() {new Thread(() -> {try {TServerSocket serverTransport = new TServerSocket(THRIFT_SERVER_PORT);// 实现类处理类classClass Processor = Class.forName(getServiceInterface() + "$Processor");// 接口Class Iface = Class.forName(getServiceInterface() + "$Iface");// 接口构造方法类Constructor con = Processor.getConstructor(Iface);// 实现类处理类TProcessor processor = (TProcessor) con.newInstance(serviceImplObject);TBinaryProtocol.Factory protocolFactory = new TBinaryProtocol.Factory(true, true);TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport);args.protocolFactory(protocolFactory);args.processor(processor);TServer server = new TThreadPoolServer(args);logger.info("Starting thrift server on port " + THRIFT_SERVER_PORT + " ..." + getServiceInterface());server.serve();} catch (Exception e) {e.printStackTrace();}}).start();}public ThriftServerProxy() {}public ThriftServerProxy(String serviceInterface, Object serviceImplObject) {this.serviceInterface = serviceInterface;this.serviceImplObject = serviceImplObject;}public String getServiceInterface() {return serviceInterface;}public void setServiceInterface(String serviceInterface) {this.serviceInterface = serviceInterface;}public Object getServiceImplObject() {return serviceImplObject;}public void setServiceImplObject(Object serviceImplObject) {this.serviceImplObject = serviceImplObject;}}

2.4 实现注解Rpc Service导入

@Slf4j
@Component
public class ThriftClientInterceptor implements BeanPostProcessor {@Resourceprivate DiscoveryClient discoveryClient;@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {Class<?> beanClass = bean.getClass();Field[] fields = beanClass.getDeclaredFields();final Random random = new Random();for (Field field : fields) {ImpThrift impThrift = field.getAnnotation(ImpThrift.class);if (Objects.isNull(impThrift)) continue;try {String serviceId = impThrift.def();List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);if (CollectionUtils.isEmpty(instances)) {// throw new ExtThriftException("instance [" + serviceId + "] not exists");log.warn("instance [{}] not exists", serviceId);}ServiceInstance serviceInstance = instances.get(random.nextInt(instances.size()));field.setAccessible(true);field.set(bean, ThriftClientProxy.getRemoteProxyObj(field.getType(), serviceInstance.getHost()));} catch (IllegalAccessException e) {e.printStackTrace();}}return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);}
}

2.5 实现注解Rpc Service导出

@Component
public class ThriftServerInterceptor implements BeanPostProcessor {@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {ExtThrift extThrift = bean.getClass().getAnnotation(ExtThrift.class);if (!Objects.isNull(extThrift)) {// String serviceName = extThrift.serviceName();Class<?>[] interfaces = bean.getClass().getInterfaces();ThriftServerProxy thriftServerProxy = new ThriftServerProxy(interfaces[0].getName().replace("$Iface", ""), bean);thriftServerProxy.start();}return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);}
}

2.6 A服务引入含有thrift生成的service的SDK对Service进行实现

@ExtThrift(serviceName = "HelloWorldService")
@Service
public class HelloWorldServiceImpl implements HelloWorldService.Iface {@Overridepublic String sayHello(String username) throws TException {return username;}
}
@RestController
@Slf4j
public class PaymentController {@Value("${server.port}")private String serverPort;@Autowiredprivate HelloWorldService.Iface helloWorldService;@RequestMapping(value = "/payment/zk")public String paymentZk(@RequestParam("username") String username) throws TException {return "SpringCloud with zookeeper: " + serverPort + "\t" + UUID.randomUUID() + "-" + helloWorldService.sayHello(username);}
}

2.7 B服务引入含有thrift生成的service的SDK和A服务进行调用

@RestController
@Slf4j
public class OrderController {@Value("${server.port}")private String serverPort;@ImpThrift(def = "CLOUD-PAYMENT-SERVICE", serviceName = "helloWorldService")private HelloWorldService.Iface helloWorldService;@RequestMapping(value = "/payment/zk")public String paymentZk(@RequestParam("username") String username) throws TException {return "SpringCloud with zookeeper: " + serverPort + "\t" + UUID.randomUUID() + "-" + helloWorldService.sayHello(username);}
}

2.8 启动zk

zhinian@192 bin % ./zkServer.sh start
ZooKeeper JMX enabled by default
Using config: /Users/zhinian/Desktop/tools/zookeeper-3.4.11/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED

2.9 启动AB服务进行测试

在这里插入图片描述
验证
调用成功 !

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/639339.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MBR扇区修复和GRUB引导修复实验

修复MBR扇区 步骤一&#xff1a;在进行实验之前我们需要新加一块磁盘&#xff0c;并对新加磁盘进行分区处理&#xff0c;用来备份sda磁盘的MBR及分区表信息。&#xff08;注&#xff1a;在实验中可以不像我如此这么繁琐&#xff0c;一个主分区&#xff0c;并格式化挂载即可&am…

Android 通过adb命令查看应用流量

一. 获取应用pid号 通过adb shell ps | grep 包名 来获取app的 pid号 二. 查看应用流量情况 使用adb shell cat /proc/#pid#/net/dev 命令 来获取流量数据 备注&#xff1a; Recevice: 表示收包 Transmit: 表示发包 bytes: 表示收发的字节数 packets: 表示收发正确的包量…

【GitHub项目推荐--不错的 C 开源项目】【转载】

大学时接触的第一门语言就是 C语言&#xff0c;虽然距 C语言创立已过了40多年&#xff0c;但其经典性和可移植性任然是当今众多高级语言中不可忽视的&#xff0c;想要学好其他的高级语言&#xff0c;最好是先从掌握 C语言入手。 今天老逛盘点 GitHub 上不错的 C语言 开源项目&…

【代码随想录11】239. 滑动窗口最大值 347. 前 K 个高频元素

目录 239. 滑动窗口最大值题目描述做题思路参考代码 347. 前 K 个高频元素题目描述参考代码 239. 滑动窗口最大值 题目描述 给你一个整数数组 nums&#xff0c;有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每…

详解C语言中`||`的短路机制

在C语言中&#xff0c;逻辑或运算符&#xff08;||&#xff09;是一种常用的逻辑运算符&#xff0c;用于组合多个条件表达式。与其他编程语言一样&#xff0c;C语言中的逻辑或运算符具有短路机制&#xff0c;这是一种非常重要的概念&#xff0c;本文将深入解释C语言中的||短路机…

MSVS C# Matlab的混合编程系列2 - 构建一个复杂(含多个M文件)的动态库:

前言: 本节我们尝试将一个有很多函数和文件的Matlab算法文件集成到C#的项目里面。 本文缩语: MT = Matlab 问题提出: 1 我们有一个比较复杂的Matlab文件: 这个MATLAB的算法,写了很多的算法函数在其他的M文件里面,这样,前面博客的方法就不够用了。会报错: 解决办法如下…

华为机考入门python3--(0)模拟题2-vowel元音字母翻译

分类&#xff1a;字符串 知识点&#xff1a; 字符串转list&#xff0c;每个字符成为list中的一个元素 list(string) 字符串变大小写 str.upper(), str.lower() 题目来自【华为招聘模拟考试】 # If you need to import additional packages or classes, please import …

分享5款简单实用的软件,值得收藏

​ 电脑上的各类软件有很多&#xff0c;除了那些常见的大众化软件&#xff0c;还有很多不为人知的小众软件&#xff0c;专注于实用功能&#xff0c;简洁干净、功能强悍。 1.自定义图标——TileIconifier ​ TileIconifier 是一款可以自定义 Windows 开始菜单图标的软件&#…

蓝牙运动耳机什么牌子的好?2024年运动无线耳机推荐

​在选择运动耳机时&#xff0c;我们需要综合考虑音质、舒适度以及适应不同运动场景的能力。好的运动耳机能够提高运动效率&#xff0c;增添锻炼的乐趣。今天&#xff0c;我为大家介绍几款在音质、佩戴舒适度、防水防汗等方面表现卓越的运动耳机&#xff0c;助你选购最适合的一…

04 单链表

目录 链表的概念和结构单链表OJ练习 1. 链表的概念和结构 1.1 链表的概念 链表是一种物理存储结构上非连续、非顺序的存储结构&#xff0c;数据元素的逻辑顺序是通过链表中的指针链接次序实现的 1.从上图可以看出链式结构在逻辑上是连续的&#xff0c;物理上不一定连续 2.现…

Docker(十)Docker Compose

作者主页&#xff1a; 正函数的个人主页 文章收录专栏&#xff1a; Docker 欢迎大家点赞 &#x1f44d; 收藏 ⭐ 加关注哦&#xff01; Docker Compose 项目 Docker Compose 是 Docker 官方编排&#xff08;Orchestration&#xff09;项目之一&#xff0c;负责快速的部署分布式…

Vue diff原理

✨ 专栏介绍 在当今Web开发领域中&#xff0c;构建交互性强、可复用且易于维护的用户界面是至关重要的。而Vue.js作为一款现代化且流行的JavaScript框架&#xff0c;正是为了满足这些需求而诞生。它采用了MVVM架构模式&#xff0c;并通过数据驱动和组件化的方式&#xff0c;使…

Golang leetcode28 找出字符串中第一个匹配项的下标 KMP算法详解

文章目录 找出字符串中第一个匹配项的下标 leetcode28 串的模式匹配问题暴力求解使用KMP模式匹配算法KMP算法简述 KMP算法的代码实现 找出字符串中第一个匹配项的下标 leetcode28 串的模式匹配问题 暴力求解 func strStr(haystack string, needle string) int { L : len(need…

wayland(wl_shell) + egl + opengles 最简实例

文章目录 前言一、ubuntu 上相关环境准备1. ubuntu 上安装 weston2. 确定ubuntu 上安装的opengles 版本3. 确定安装的 weston 是否支持 wl_shell 接口二、窗口管理器接口 wl_shell 介绍二、代码实例1.egl_wayland_demo.c2. 编译和运行2.1 编译2.2 运行总结参考资料前言 本文主…

UE5 C++学习笔记 FString FName FText相互转换

1.FString 是UE里的String。最接近std::string, 唯一可以修改的字符串类型。性能更低 TEXT(string) TEXT宏&#xff0c;作用是将字符串转换成Unicode&#xff0c;切记UE中使用字符串输出要使用该宏 2. FName 是UE里特有的类型。它更注重于表示名称不区分大小写&#xff0c;不…

基于taro搭建小程序多项目框架,记重点了!!!

前言 为什么需要这样一个框架&#xff0c;以及这个框架带来的好处是什么&#xff1f; 从字面意思上理解&#xff1a;该框架可以用来同时管理多个小程序&#xff0c;并且可以抽离公用组件或业务逻辑供各个小程序使用。当你工作中面临这种同时维护多个小程序的业务场景时&#…

web架构师编辑器内容-完成属性设置的优化

对于业务组件来说&#xff0c;其属性是有很多的&#xff0c;如果把所有属性都平铺在页面上&#xff0c;就会非常长&#xff0c;而且想要更改其中的某些属性&#xff0c;可能需要向下滚动很久才能找到&#xff0c;对于UI的交互不是很友好&#xff0c;需要对属性的不同特性进行分…

KDJ指标的算法、原理和特性

KDJ的完整中文名称是随机摆动指标&#xff0c;是短线交易者最常用的指标之一。作为应用最广泛的指标之一&#xff0c;KDJ的用法网上随处可见&#xff0c;但大部分介绍都只会告诉你超买超卖&#xff0c;金叉死叉&#xff0c;详细点的讲讲背离和钝化&#xff0c;至于为什么这么用…

填空题如何去掉答案?教你3个去除小妙招

填空题如何去掉答案&#xff1f;在日常学习过程中&#xff0c;将写过的试卷填空题去掉答案&#xff0c;是一种非常有效的学习方法&#xff0c;可以帮助学生们更好地巩固和扩充知识点。首先&#xff0c;去掉答案可以让学生们重新审视题目&#xff0c;加深对知识点的理解。其次&a…

【RT-DETR有效改进】Google | EfficientNetV2一种超轻量又高效的网络 (轻量化网络)

前言 大家好&#xff0c;我是Snu77&#xff0c;这里是RT-DETR有效涨点专栏。 本专栏的内容为根据ultralytics版本的RT-DETR进行改进&#xff0c;内容持续更新&#xff0c;每周更新文章数量3-10篇。 专栏以ResNet18、ResNet50为基础修改版本&#xff0c;同时修改内容也支持Re…