代码生成类解析:
Thrift--facebook RPC框架,介绍就不说了,百度,google一大把,使用也不介绍,直接上结构和分析吧。
Hello.thrift文件内容如下:
namespace java com.tomsun.thrift.generated.demo service Hello { string helloString(1:string para) }
内容很简单,申明个RPC service(Hello),服务方法helloString,方法参数格式(seq: parameter type, parameter name),参数需要标号(1: xxx xxx, 2: xxx xxx), namespace 指定生成代码语言类型(java),和Java包名(本文只讨论java ^#^!).
类文件解析:
话说就上面定义一个service(只包含一个method),可生成的类文件可是一个庞然大物(975行代码),在此就不全贴出来了,说明时会贴出关键代码用于说明。
因为thrift是一个完整的RPC框架,内部结构分的很细,所以代码生成量理所当然,(protobuf的所谓的RPC,只不过是个架子,空的,基本上都得自己去实现。当protobuf序列化自己感觉比thrift丰富多了(sint,fint,int,uint)),
但thrift支持的容器类型(List,set, map)比protobuf多(list),具体介绍等以后再详细,回到正题。
thrift compiler生成的Hello.java 文件,以服务名为类文件名。服务接口定义如下:
1 public interface Iface { //同步RPC服务调用接口定义 2 3 public String helloString(String para) throws org.apache.thrift.TException; 4 5 } 6 7 public interface AsyncIface { //异步RPC服务调用接口定义(仔细瞅,方法返回值参数string没了,方法参数多了个AsyncMethodCallback) 8 9 public void helloString(String para, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; 10 11 }
Async形式具体返回值是通过callback回调来获得。定义如下:
1 public interface AsyncMethodCallback<T> { 2 /** 3 * This method will be called when the remote side has completed invoking 4 * your method call and the result is fully read. For oneway method calls, 5 * this method will be called as soon as we have completed writing out the 6 * request. 7 * @param response 8 */ 9 public void onComplete(T response); 10 11 /** 12 * This method will be called when there is an unexpected clientside 13 * exception. This does not include application-defined exceptions that 14 * appear in the IDL, but rather things like IOExceptions. 15 * @param exception 16 */ 17 public void onError(Exception exception); 18 }
自己定义异步RPC得实现该接口,同步RPC客户端骨架及其工厂类如下。
1 public static class Client extends org.apache.thrift.TServiceClient implements Iface { 2 public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {