thrift 简介三

2017-12-11  本文已影响0人  sunny4handsome

thrift 使用
之前我们看了一些thrift的概念,现在我们通过hello world来学习thrift的使用。

thrift idl

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

通过thrift生成对应的代码

thrift 安装

thrift 生成代码

thrift -r -gen java hello.thrift

code

pom文件

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.0</version>
        </dependency>
    </dependencies>

实现

public class HelloWorldImpl implements HelloWorldService.Iface{
    @Override
    public String sayHello(String username) throws TException {
        return "hi, "+ username;
    }
}

server

public class AppServer {
    public static void main(String[] args) {
        AppServer appServer = new AppServer();
        appServer.startServer();
    }
    public void startServer(){
        TProcessor tProcessor = new HelloWorldService.Processor<HelloWorldImpl>(new HelloWorldImpl());
        try {
            TServerSocket serverSocket = new TServerSocket(8090);
            TServer.Args tArgs = new TServer.Args(serverSocket);
            tArgs.processor(tProcessor);
            tArgs.protocolFactory(new TBinaryProtocol.Factory());
            TServer server = new TSimpleServer(tArgs);
            server.serve();
        } catch (TTransportException e) {
            e.printStackTrace();
        }

    }
}

client

public class AppClient {
    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;
        transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
        TProtocol protocol = new TBinaryProtocol(transport);
        HelloWorldService.Client client = new HelloWorldService.Client(protocol);
        try {
            transport.open();
            String result = client.sayHello(username);
            System.out.println("get server result = " + result);
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        AppClient appClient = new AppClient();
        appClient.startClient("payne");
    }
}

上面的是简单的单线程服务模型,一般用于测试。
除此之外还有模型如下:根据实际选用:

上一篇下一篇

猜你喜欢

热点阅读