Apache thrift 学习

mac下安装很方便,brew install thrift

先看传输层类图:

代码示例参考网友的git项目:

https://github.com/quxionglie/thriftDemo.git

TServer是入口,Transport是传输的实现。

Apache thrift 学习_第1张图片

看示例代码吧:

服务器端:

public static final int SERVER_PORT = 7090;

public void start() {
    try {
        System.out.println("UserServer start ....");
        TProcessor tprocessor = new UserService.Processor<UserService.Iface>(
            new UserServiceImpl());

        TServerSocket serverTransport = new TServerSocket(SERVER_PORT);
        TServer.Args tArgs = new TServer.Args(serverTransport);
        tArgs.processor(tprocessor);
        tArgs.protocolFactory(new TBinaryProtocol.Factory());
        TServer server = new TSimpleServer(tArgs);
        server.serve();

        } catch (Exception e) {
            System.out.println("Server start error!!!");
            e.printStackTrace();
    }
}

客户端:

public static final String SERVER_IP = "localhost";
public static final int SERVER_PORT = 7090;
public static final int TIMEOUT = 30000;

public void login(String userName, String passwd) {
    TTransport transport = null;
    try {
        transport = new TSocket(SERVER_IP, SERVER_PORT, TIMEOUT);
        // 协议要和服务端一致
        TProtocol protocol = new TBinaryProtocol(transport);
        UserService.Client client = new UserService.Client(protocol);
        transport.open();
        LoginResponse loginResponse = client.login(userName, passwd);
        System.out.println("Thrify client result =: " + loginResponse);
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
        if (null != transport) {
            transport.close();
        }
    }
}

这是个入门的文章:

http://www.micmiu.com/soa/rpc/thrift-sample/

这个是相关特性的介绍

http://blog.sina.com.cn/s/blog_72995dcc0101gn82.html

官方的tutorial

http://thrift.apache.org/tutorial/java



你可能感兴趣的:(Apache thrift 学习)