使用Thrift实现RPC简单示例03

接第01部分,本节用来说明Java语言的代码实现。

使用thrift生成java代码之后,会生成两个java文件,无论是Client还是Server都要包含这个文件。

首先是Server端:
1、新建一个java项目,引用libthrift.jar,项目中添加生成的两个java文件。
2、新建一个类MyThriftServer,实现JustATest.Iface接口

package com.neohope.thrift.test;

import org.apache.thrift.TException;

public class MyThriftServer implements JustATest.Iface {
    @Override
    public String SayHelloTo(Person person) throws TException {
        return "Hello "+ person.getName();
    }

    @Override
    public int Add(int a, int b) throws TException {
        return a+b;
    }
}

3、修改TestServer.java

package com.neohope.thrift.test;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;

public class TestServer {
    public static void main(String[] args) {
        try {
            TServerSocket serverTransport = new TServerSocket(1900);
            JustATest.Processor process = new JustATest.Processor(new MyThriftServer());
            TBinaryProtocol.Factory portFactory = new TBinaryProtocol.Factory(true, true);
            TThreadPoolServer.Args thriftArgs = new TThreadPoolServer.Args(serverTransport);
            thriftArgs.processor(process);
            thriftArgs.protocolFactory(portFactory);
            TServer server = new TThreadPoolServer(thriftArgs);
            server.serve();
        } catch (TTransportException e) {
            e.printStackTrace();
        }
    }
}

4、编译运行

然后是Client端:
1、新建一个java项目,引用libthrift.jar,项目中添加生成的两个java文件。
2、修改TestClient.java

package com.neohope.thrift.test;

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 org.apache.thrift.transport.TTransportException;

public class TestClient {

    public static void main(String[] args) {
        TTransport transport;
        try {
            transport = new TSocket("localhost", 1900);
            TProtocol protocol = new TBinaryProtocol(transport);
            JustATest.Client client = new JustATest.Client(protocol);
            transport.open();

            Person p = new Person();
            p.setName("neohope");
            System.out.println(client.SayHelloTo(p));
            System.out.println(client.Add(1, 2));
            transport.close();
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        }
    }
}

3、编译运行

Leave a Reply

Your email address will not be published. Required fields are marked *

*