server端代码:
package thrift.nan.demoImpl; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.thrift.TProcessorFactory; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TSimpleJSONProtocol; import org.apache.thrift.server.*; import org.apache.thrift.transport.*; import thrift.nan.demo.PersonService; /** * 发布服务接口 */ public class PersonServer { public static void main(String[] args) throws Exception { TNonblockingServerSocket serverSocket=new TNonblockingServerSocket(8899); THsHaServer.Args arg=new THsHaServer.Args(serverSocket).minWorkerThreads(2).maxWorkerThreads(4); PersonService.Processor<PersonServiceImpl> processor=new PersonService.Processor<>(new PersonServiceImpl()); //需要注意的是服务器端使用的传输协议 要和客户端使用的传输协议一致 /** * thrift中定义的传输协议有: * new TBinaryProtocol.Factory() 二进制文件格式 * new TCompactProtocol.Factory() 压缩格式 (二进制的基础上更加压缩) * new TSimpleJSONProtocol.Factory() Json格式 * new TSimpleJSONProtocol.Factory() 很少用,提供Json的只写协议 */ arg.protocolFactory(new TCompactProtocol.Factory()); /** * thrift 数据传输方式 * new TSocket.Factory() 阻塞式 效率最低 * new TFramedTransport.Factory() 以frame为单位(把数据切分成一个一个的frame)进行传输,非阻塞式 * new TFileTransport() 以文件形式进行传输 * TMemoryInputTransport java 底层实际使用的是ByteArrayOutputStream */ arg.transportFactory(new TFramedTransport.Factory()); arg.processorFactory(new TProcessorFactory(processor)); /** * thrift 支持的服务模型 * TSimpleServer 简单的单线程服务模型 用于测试 * TThreadPoolServer 多线程服务模型 使用标准的阻塞式IO * TNonblockingServer 多线程服务模型 使用非阻塞式IO (需要制定传输方式是TFramedTransport) * THsHaServer 引入了线程池 更加高效 */ TServer server=new THsHaServer(arg); System.out.println("服务接口开始发布"); server.serve(); } }
client端代码
package thrift.nan.demoClient; 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 thrift.nan.demo.Person; import thrift.nan.demo.PersonService; public class PersonClient { public static void main(String[] args) throws Exception { TTransport transport=new TFramedTransport(new TSocket("localhost",8899),600); TProtocol protocol=new TCompactProtocol(transport); PersonService.Client client=new PersonService.Client(protocol); try{ transport.open(); Person person=client.getPersonByUserName("jake"); System.out.println(((Person) person).getUserName()); System.out.println(person.getAge()); System.out.println("---------------------------"); person.setUserName("tom"); client.savePerson(person); }catch (Exception e){ throw new RuntimeException(e.getMessage(),e); }finally { transport.close(); } } }