关闭

thrift rpc框架入门

标签: rpcthrift
374人阅读 评论(0) 收藏 举报
分类:

thrift 入门

  1. 下载thrift:wget http://ftp.kddilabs.jp/infosystems/apache/thrift/0.9.3/thrift-0.9.3.tar.gz
  2. 解压:tar -zxvf thrift-0.9.3.tar.gz
  3. 安装: ./configure && make && make install
  4. 编写thrift文件:
    (dto.thrift)
namespace java com.terry.thrift.dto
struct Person {
    1: string username,
    2: string password
}

(service.thrift)

namespace java  com.terry.thrift.service
include "dto.thrift"
service PersonService {
    dto.Person get(1:string username)
}

4.1 编译thrift文件:

thrift -gen java dto.thrift 
thrift -gen java service.thrift 

4.2 把生成的文件导入工程

  1. 服务实现:
public class PersonServiceImpl implements PersonService.Iface {

    @Override
    public Person get(String username) throws TException {
        System.out.println("client param: " + username);
        Person p = new Person();
        p.setPassword("password");
        p.setUsername("username");
        return p;
    }
}
  1. 服务启动测试:
public class ThriftServer {

    private static PersonService.Iface service;
    private static PersonService.Processor process;

    public static void main(String[] args) {
        service = new PersonServiceImpl();
        process = new PersonService.Processor(service);
        Runnable simple = new Runnable() {
            public void run() {
                simple(process);
            }
        };
        new Thread(simple).start();
    }
    public static void simple(PersonService.Processor processor) {
        try {
            TServerTransport serverTransport = new TServerSocket(9090);
            TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
            System.out.println("Starting the simple server...");
            server.serve();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  1. 客户端测试:
public class ThriftClient {

    public static void main(String[] args) throws Exception{
        TTransport transport = new TSocket("localhost", 9090);
        transport.open();
        TProtocol p = new TBinaryProtocol(transport);
        PersonService.Client client = new PersonService.Client(p);
        Person person = client.get("name");
        System.out.println(person);

    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:198428次
    • 积分:2781
    • 等级:
    • 排名:第13375名
    • 原创:105篇
    • 转载:3篇
    • 译文:0篇
    • 评论:19条
    最新评论