ppt0501的专栏

开始工作,留下点滴

thrift rpc框架入门

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);

    }
}
阅读更多
文章标签: rpc thrift
个人分类: java后台
上一篇java访问redis集群服务器
下一篇dobbu入门
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭