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.hqwc.cn/news/421756.html

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

相关文章

Android OpenGL EGL使用——自定义相机

如果要使用OpenGl来自定义相机&#xff0c;EGL还是需要了解下的。 可能大多数开发者使用过OpengGL但是不知道EGL是什么&#xff1f;EGL的作用是什么&#xff1f;这其实一点都不奇怪&#xff0c;因为Android中的GlSurfaceView已经将EGL环境都给配置好了&#xff0c;你一直在使用…

数据操作——Column 对象

Column 对象 1. 什么是Column对象 Column 表示了 Dataset 中的一个列, 并且可以持有一个表达式, 这个表达式作用于每一条数据, 对每条数据都生成一个值 2.Column对象如何创建 ’ 单引号 ’ 在 Scala 中是一个特殊的符号, 通过 ’ 会生成一个 Symbol 对象, Symbol 对象可以理…

《SPSS统计学基础与实证研究应用精解》视频讲解:SPSS数据查找

《SPSS统计学基础与实证研究应用精解》4.4 视频讲解 视频为《SPSS统计学基础与实证研究应用精解》张甜 杨维忠著 清华大学出版社 一书的随书赠送视频讲解4.4节内容。本书已正式出版上市&#xff0c;当当、京东、淘宝等平台热销中&#xff0c;搜索书名即可。本书旨在手把手教会使…

【QT+QGIS跨平台编译】之三:【OpenSSL+Qt跨平台编译】(一套代码、一套框架,跨平台编译)

文章目录 一、OpenSSL介绍二、OpenSSL配置三、Window环境下配置四、Linux环境下配置五、Mac环境下配置 一、OpenSSL介绍 OpenSSL是一个开放源代码的软件库包&#xff0c;应用程序可以使用这个包来进行安全通信&#xff0c;避免窃听&#xff0c;同时确认另一端连接者的身份。这…

Python文件操作和异常处理:高效处理数据的利器

文章目录 一、引言1.1 文件操作和异常处理对于编程的重要性1.2 Python作为实现文件操作和异常处理的强大工具 二、为什么学习文件操作和异常处理2.1 处理各种文件格式&#xff1a;从文本到图像到音频等2.2 确保代码的鲁棒性&#xff1a;有效处理异常情况 三、文件读取和写入3.1…

2023年12月 Scratch 图形化(二级)真题解析#中国电子学会#全国青少年软件编程等级考试

Scratch图形化等级考试(1~4级)全部真题・点这里 一、单选题(共25题,每题2分,共50分) 第1题 在制作推箱子游戏时,地图是用数字形式储存在电脑里的,下图是一个推箱子地图,地图表示如下: 第一行(111111) 第二行(132231) 第三行(126621) 第四行( ) 第五行(152…

网络安全全栈培训笔记(56-服务攻防-数据库安全H2ElasticsearchCouchDBInfluxdb复现)

第56天 服务攻防-数据库安全&H2&Elasticsearch&CouchDB&Influxdb复现 知识点&#xff1a; 1、服务攻防数据库类型安全 2、influxdb,.未授权访问wt验证 3、H2 database-未授权访问-配置不当 4、CouchDB-权限绕过配合RCE-漏洞 5、ElasticSearch-文件写入&RC…

vue3前端开发,一篇文章看懂何谓pinia

vue3前端开发,pinia的基础练习第一节&#xff01; 前言&#xff0c;pinia是为了取代vuex而诞生的产品&#xff0c;它有一些改进。去掉了之前的mutations。只有一个action,既可以支持异步&#xff0c;又支持同步。还提供了解构函数&#xff0c;可以把返回的对象内部属性和方法直…

给创业者的一份忠告~创业就要选择低成本的轻资产创业项目

王健林继续出售资产&#xff0c;5天卖了4座万达广场&#xff0c;出售计划仍在继续..... 根据天眼查app最新消息&#xff0c;厦门殿前万达广场商业管理有限公司发生工商变更&#xff0c;2023至今已经转让10座万达广场。两年前万达旗下的核心子公司万达商管&#xff0c;向一群投资…

xxe漏洞之scms靶场漏洞

xxe-scms 代码审核 &#xff08;1&#xff09;全局搜索simplexml_load_string simplexml_load_string--将XML字符串解释为对象 &#xff08;2&#xff09;查看源代码 ID1 $GLOBALS[HTTP_RAW_POST_DATA]就相当于file_get_contents("php://input"); 因此这里就存…

偷偷浏览小网站时,原来有这么多人已经知道

最近看到一篇挺有意思文章&#xff0c;偷偷浏览小网站时&#xff0c;都有谁会知道你看了啥。思量之下&#xff0c;从更广泛的技术角度看&#xff0c;仍有大量补充的空间&#xff0c;于是就有了这样一篇文章。本文的目的在于增强大家的网络安全意识&#xff0c;非必要不要浏览不…

【Web实操11】定位实操_照片墙(无序摆放)

设置一个板块&#xff0c;将照片随意无序摆放在墙上&#xff0c;从而形成照片墙。本来效果应该是很唯美好看的&#xff0c;就像这种&#xff0c;但是奈何本人手太笨&#xff0c;只好设置能达到照片墙的效果就可。 代码如下&#xff1a; <!DOCTYPE html> <html lang&…