Thrift是一种接口描述语言和二进制通讯协议,它被用来定义和创建跨语言的服务。它被当作一个远程过程调用(RPC)框架来使用
下载地址:
http://mirror.bit.edu.cn/apache/thrift/
官方文档
http://thrift.apache.org/
namespace java netty.thrift
typedef i16 short
typedef i32 int
typedef i64 long
typedef string String
typedef bool boolean
struct Person{
1: optional String username;
2: optional int age;
3: optional boolean married;
}
exception MessageException{
1: optional String message,
2: optional String callStack,
3: optional String date,
}
service PersonService{
Person getPersonByName(1:required String username) throws (1:MessageException messageException);
}
用 thrift -gen java D:\Thrift\auth.thrift可以生成Java代码
服务器代码
public class ThriftServer {
public static void main(String[] args) throws Exception {
//创建非阻塞式socket
TNonblockingServerSocket socket = new TNonblockingServerSocket(8080);
//io异步handle同步服务
THsHaServer.Args arg = new THsHaServer.Args(socket).minWorkerThreads(2).maxWorkerThreads(4);
PersonService.Processor <PersonServiceImpl> processor = new PersonService.Processor <>(new PersonServiceImpl());
arg.protocolFactory(new TCompactProtocol.Factory());
arg.transportFactory(new TFramedTransport.Factory());
arg.processorFactory(new TProcessorFactory(processor));
TServer server = new THsHaServer(arg);
System.out.println("Thrift server started!");
server.serve();
}
}
客户端代码
public class ThriftClient {
public static void main(String[] args) {
//绑定运输地址
TTransport transport = new TFramedTransport(new TSocket("localhost", 8080), 600);
//通信协议
TCompactProtocol protocol = new TCompactProtocol(transport);
//service
PersonService.Client client = new PersonService.Client(protocol);
try {
transport.open();
Person person = client.getPersonByName("张三");
System.out.println(person.getAge());
System.out.println(person.getUsername());
System.out.println(person);
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
} finally {
transport.close();
}
}
}