宾川网站建设,推广你公司网站,制作一个完整的网页的步骤,单页网站 挣钱写在前面
本文一起看下一种由facebook出品的rpc框架thrift。 源码 。 1#xff1a;开发步骤
1:编写thrift idl文件
2#xff1a;根据thrift idl文件生成java模板代码
3#xff1a;继承模板代码的*.Iface接口给出server的具体服务实现
4#xff1a;使用模板的HelloWorldSe…写在前面
本文一起看下一种由facebook出品的rpc框架thrift。 源码 。 1开发步骤
1:编写thrift idl文件
2根据thrift idl文件生成java模板代码
3继承模板代码的*.Iface接口给出server的具体服务实现
4使用模板的HelloWorldService.Processor编写server端
5使用HelloWorldService.Client编写服务端调用程序2实战 准备编译生成器 这里 。 idea准备插件 无该步骤也可以 编写idl hello.thrift:
service HelloWorldService {string say(1: string username)
}通过生成器生成模板文件
$ ./thrift-0.19.0.exe -gen java hello.thrift生成的模板Java文件很长主要关注如下几个类即可
Iface服务端通过实现此接口提供同步服务
AsyncIface服务端通过实现此接口提供异步服务
Client:客户端通过此类的实例对象以同步的方式访问服务端
AysyncClient客户端通过此类的是实例以异步的方式访问服务端将生成的代码拷贝到项目备用。
pom
dependencygroupIdorg.apache.thrift/groupIdartifactIdlibthrift/artifactIdversion0.19.0/version
/dependencyservice实现类
public class HelloWorldServiceImpl implements HelloWorldService.Iface {Overridepublic String say(String username) throws TException {return Hello username;}
}server类
public class SimpleServer {public static void main(String[] args) throws Exception {ServerSocket serverSocket new ServerSocket(ServerConfig.SERVER_PORT);TServerSocket serverTransport new TServerSocket(serverSocket);HelloWorldService.Processor processor new HelloWorldService.ProcessorHelloWorldService.Iface(new HelloWorldServiceImpl());TBinaryProtocol.Factory protocolFactory new TBinaryProtocol.Factory();TSimpleServer.Args tArgs new TSimpleServer.Args(serverTransport);tArgs.processor(processor);tArgs.protocolFactory(protocolFactory);// 简单的单线程服务模型 一般用于测试TServer tServer new TSimpleServer(tArgs);System.out.println(Running Simple Server);tServer.serve();}
}启动。
client类
public class SimpleClient {public static void main(String[] args) {TTransport transport null;try {transport new TSocket(ServerConfig.SERVER_IP, ServerConfig.SERVER_PORT, ServerConfig.TIMEOUT);TProtocol protocol new TBinaryProtocol(transport);HelloWorldService.Client client new HelloWorldService.Client(protocol);transport.open();String result client.say(Leo);System.out.println(Result : result);} catch (TException e) {e.printStackTrace();} finally {if (null ! transport) {transport.close();}}}
}运行
Result : Hello LeoProcess finished with exit code 0酱
写在后面
参考文章列表
Apache Thrift系列详解(一) - 概述与入门 。