netty学习笔记9-thrift入门

需求:

使用thrift完成简单的RPC的通信

1. 编写.thrift文件(idl文件)

namespace java com.baidu.thrift
typedef i32 int
typedef bool boolean
typedef string String
struct Person{
    1: int age,
    2: String name,
    3: boolean married
}
exception DataNotFound {
    1: int code,
    2: String message
}
service PersonService
{
    Person getPersonByName(1: String name) throws (1: DataNotFound e);
    void savePerson(1: Person p) throws(1: DataNotFound e);
}

2. 使用thrift的工具生成Java文件(需要先下载)

thrift --gen java .thrift文件的路径

3. 编写实现thrift生成的接口

package com.baidu.thrift;

import org.apache.thrift.TException;

public class PersonServiceImpl implements PersonService.Iface {
    @Override
    public Person getPersonByName(String name) throws DataNotFound, TException {
        return new Person().setAge(18).setName("admin").setMarried(true);
    }

    @Override
    public void savePerson(Person p) throws DataNotFound, TException {
        System.out.println(p.getName() + " : " + p.getAge() + " : " + p.isMarried());
    }
}

4. 编写RPC的服务器端

package com.baidu.thrift;

import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;

public class MyServer {
    public static void main(String[] args) throws Exception {
        TNonblockingServerSocket serverSocket = new TNonblockingServerSocket(8899,6000);
        THsHaServer.Args arg = new THsHaServer.Args(serverSocket);
        PersonService.Processor processor = new PersonService.Processor(new PersonServiceImpl());
        arg.transportFactory(new TFramedTransport.Factory());
        arg.protocolFactory(new TCompactProtocol.Factory());
        arg.processorFactory(new TProcessorFactory(processor));

        THsHaServer server = new THsHaServer(arg);
        server.serve();
    }
}

5. 编写RPC的客户端

package com.baidu.thrift;

import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import sun.rmi.transport.Transport;

public class MyClient {
    public static void main(String[] args) throws Exception{
        TTransport transport = new TFramedTransport(new TSocket("localhost",8899),600);
        TProtocol protocol = new TCompactProtocol(transport);

        PersonService.Client personService = new PersonService.Client(protocol);
        transport.open();

        Person person = personService.getPersonByName("admin");
        System.out.println(person.getName());
        Person p = new Person().setAge(19).setMarried(false).setName("老徐");
        personService.savePerson(p);
        transport.close();
    }
}

你可能感兴趣的:(netty自学笔记)