Thrift框架Demo

2020-04-28  本文已影响0人  insomniaLee

简介

rpc框架,用于服务之间进行rpc通讯,跨语言,通过中间语言IDL来联系客户端和服务器。

helloworld

引入maven依赖

<dependency>    
            <groupId>org.apache.thrift</groupId>   
            <artifactId>libthrift</artifactId>    
            <version>0.8.0</version>
</dependency>
<dependency>    
          <groupId>org.slf4j</groupId>    
          <artifactId>slf4j-log4j12</artifactId>    
          <version>1.5.8</version>
</dependency>

编写IDL代码

service  HelloWorldService {
        string sayHello(1:string username)
}

IDL代码转换成目标语言

因为我使用的是java,所以可以使用:

thrift -gen java demoHello.thrift

来将其转化为java语言的代码。
除了命令行工具,也可以使用一些在线网站来将代码转化成目标语言。

定义服务提供者

public class HelloServerDemo {
    public static void main(String[] args) throws IOException, TTransportException {
        final int SERVER_PORT = 8090;
        ServerSocket socket = new ServerSocket(SERVER_PORT);
        TServerSocket serverTransport = new TServerSocket(socket);
        HelloWorldService.Processor processor = new HelloWorldService.Processor(new HelloWorldImpl());
        TServer.Args tArgs = new TServer.Args(serverTransport);
        tArgs.processor(processor);
        tArgs.protocolFactory(new TBinaryProtocol.Factory());
        TServer server = new TSimpleServer(tArgs);

        System.out.println("Running server...");
        server.serve();
    }
}

服务消费者

public class HelloClientDemo {
    public static final String SERVER_IP = "localhost";
    public static final int SERVER_PORT = 8090;
    public static final int TIMEOUT = 30000;
    public void startClient(String userName) {
        TTransport transport = null;
        try {
            transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
            TProtocol protocol = new TBinaryProtocol(transport);
            HelloWorldService.Client client = new HelloWorldService.Client(
                    protocol);
            transport.open();
            String result = client.sayHello(userName);
            System.out.println("Thrify client result =: " + result);
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            if (null != transport) {
                transport.close();
            }
        }
    }
    public static void main(String[] args) {
        HelloClientDemo client = new HelloClientDemo();
        client.startClient("insomnia");
    }
}

执行

先启动server在启动client即可。


以上为一个thrift bs服务的简单dmeo

上一篇下一篇

猜你喜欢

热点阅读