thrift远程调用示例

来源:互联网 发布:springerlink数据库 编辑:程序博客网 时间:2024/05/22 13:10

thrift是facebook研发的跨语言的RPC框架,这次我们来编写一个thrift调用的示例。
需要首先定义一个数据结构,用文本编辑器,然后通过thrift编译成不同语言的文件,这是实现跨平台的关键步骤,这次我演示的是将定义的数据结构文件编译成java的类。
1.首先去thrift官网下载编译工具。(windows下是thrift-[版本号].exe)
我们用文本编辑器定义一个简单的数据结构,这里就写个HelloWorld:

namespace java com.micro.thriftDemo// 服务名service HelloWorldService {    string sayHello(1: string name);}

然后修改该文件的格式为.thrift
thrift定义结构的语法规则可以查找相关资料。
然后cmd到对应目录下编译该文件。
命令如下:

thrift-0.9.3.exe -gen java Test.thrift

生成文件夹 gen-java,对应里面是java包和类文件。
3.接下来我们来构建maven项目:

        <dependency>            <groupId>org.apache.thrift</groupId>            <artifactId>libthrift</artifactId>            <version>0.9.3</version>            <type>pom</type>        </dependency>

这里写图片描述
这里要分为服务端和客户端模拟RPC,将编译好的文件复制到对应的目录下面,注意jdk编译环境修改成1.8否则会报错。
服务端Server编写如下:

import org.apache.thrift.TException;import org.apache.thrift.server.TServer;import org.apache.thrift.server.TSimpleServer;import org.apache.thrift.transport.TServerSocket;import org.apache.thrift.transport.TServerTransport;import org.apache.thrift.transport.TTransportException;import org.apache.thrift.server.TServer.Args;  import com.micro.thriftDemo.HelloWorldService;/** *  * @author mapc * Server.java * 2016年7月14日 * @Description */public class Server {    public static class HelloWorldServiceImpl implements HelloWorldService.Iface{        @Override        public String sayHello(String name) throws TException {            return "hello  world! i am implements Iface";        }    }    public static void main(String[] args) throws TTransportException {        // 获取实现        HelloWorldServiceImpl impl= new HelloWorldServiceImpl();        // 接口与实现类的绑定关系在这里完成        HelloWorldService.Processor<HelloWorldServiceImpl> processor = new HelloWorldService.Processor<HelloWorldServiceImpl>(impl);        // 构建服务器        TServerTransport serverTransport = new TServerSocket(9090);        TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));        System.out.println("Starting the thrift server ...");        server.serve();    }}

客户端Client编写如下:

package com.thrift_demo;import org.apache.thrift.TException;import org.apache.thrift.protocol.TBinaryProtocol;import org.apache.thrift.protocol.TProtocol;import org.apache.thrift.transport.TSocket;import org.apache.thrift.transport.TTransport;import com.micro.thriftDemo.HelloWorldService;public class Client {    public static void main(String[] args) throws TException {        TTransport transport = new TSocket("localhost", 9090);        transport.open();        TProtocol protocol = new TBinaryProtocol(transport);        HelloWorldService.Client client = new HelloWorldService.Client(protocol);        String result = client.sayHello("micro");        System.out.println("调用结果:" + result);        transport.close();    }}

4.首先启动Server

Starting the thrift server ...

执行Client

调用结果:hello  world! i am implements Iface

这样客户端就可以直接调用接口,而不用关心具体的实现类了。实现了PRC的功能。

1 0
原创粉丝点击