java 转 thrift_Thrift入门及Java实例演示【转】

实现接口Iface

Java代码:HelloWorldImpl.java

packagecom.thrift.demo;importorg.apache.thrift.TException;public class HelloWorldImpl implementsHelloWorldService.Iface {publicHelloWorldImpl() {

}

@Overridepublic String sayHello(String username) throwsTException {return "Hi," + username + " welcome to thrift demo world";

}

}

TSimpleServer服务端

简单的单线程服务模型,一般用于测试。

编写服务端server代码:ThriftServer.java

packagecom.thrift.demo.server;importorg.apache.thrift.TProcessor;importorg.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.protocol.TBinaryProtocol.Factory;importorg.apache.thrift.server.TServer;importorg.apache.thrift.server.TSimpleServer;importorg.apache.thrift.transport.TFramedTransport;importorg.apache.thrift.transport.TServerSocket;importorg.apache.thrift.transport.TTransportException;importorg.apache.thrift.transport.TTransportFactory;importcom.thrift.demo.service.HelloWorldService;importcom.thrift.demo.service.impl.HelloWorldServiceImpl;/**************************************************************

* @类名 ThriftServer

*

* @AUTHOR Neo

*************************************************************/

public classThriftServerDemo {public voidstartServer() {try{

System.out.println("Starting Thrift Server......");

TProcessor processor= new HelloWorldService.Processor(newHelloWorldServiceImpl());

TServerSocket serverTransport= new TServerSocket(8191);

TTransportFactory transportFactory= newTFramedTransport.Factory();

Factory factory= newTBinaryProtocol.Factory();

TServer.Args tArgs= newTServer.Args(serverTransport);

tArgs.protocolFactory(factory);

tArgs.transportFactory(transportFactory);

tArgs.processor(processor);//简单的单线程服务模型,一般用于测试

TServer server = newTSimpleServer(tArgs);

server.serve();

}catch(TTransportException e) {

System.out.println("Starting Thrift Server......Error!!!");

e.printStackTrace();

}

}public static voidmain(String[] args) {

ThriftServerDemo server= newThriftServerDemo();

server.startServer();

}

}

编写客户端Client代码:ThriftClientDemo.java

packagecom.thrift.demo.client;importorg.apache.thrift.TException;importorg.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.protocol.TProtocol;importorg.apache.thrift.transport.TFramedTransport;importorg.apache.thrift.transport.TSocket;importorg.apache.thrift.transport.TTransport;importorg.apache.thrift.transport.TTransportException;importcom.thrift.demo.service.HelloWorldService;importcom.thrift.demo.service.HelloWorldService.Client;/**************************************************************

* @类名 ThriftClient

*

* @AUTHOR Neo

*************************************************************/

public classThriftClientDemo {public static voidmain(String[] args) {try{

TTransport transport= new TFramedTransport(new TSocket("127.0.0.1", 8191, 5000));//协议要和服务端一致

TProtocol protocol = newTBinaryProtocol(transport);

Client client= newHelloWorldService.Client(protocol);

transport.open();

String string= client.sayHello("Neo");

System.out.println(string);

transport.close();

}catch(TTransportException e) {

e.printStackTrace();

}catch(TException e) {

e.printStackTrace();

}

}

}

先运行服务端程序,日志如下:

Starting Thrift Server......

再运行客户端调用程序,日志如下:

Hello World,Hello Thrift!!! Hi:Neo

测试成功,和预期的返回信息一致。

TThreadPoolServer 服务模型

线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。

编写服务端代码:HelloServerDemo.java

packagecom.thrift.demo.server;importorg.apache.thrift.TProcessor;importorg.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.server.TServer;importorg.apache.thrift.server.TThreadPoolServer;importorg.apache.thrift.transport.TServerSocket;importcom.thrift.demo.service.HelloWorldService;importcom.thrift.demo.service.impl.HelloWorldServiceImpl;/**************************************************************

* @类名 HelloServerDemo

*

* @AUTHOR Neo

*************************************************************/

public classHelloServerDemo {public static final int SERVER_PORT = 8191;public voidstartServer() {try{

System.out.println("HelloWorld TThreadPoolServer start ....");

TProcessor tprocessor= new HelloWorldService.Processor(newHelloWorldServiceImpl());

TServerSocket serverTransport= newTServerSocket(SERVER_PORT);

TThreadPoolServer.Args ttpsArgs= newTThreadPoolServer.Args(serverTransport);

ttpsArgs.processor(tprocessor);

ttpsArgs.protocolFactory(newTBinaryProtocol.Factory());//线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。

TServer server = newTThreadPoolServer(ttpsArgs);

server.serve();

}catch(Exception e) {

System.out.println("Server start error!!!");

e.printStackTrace();

}

}public static voidmain(String[] args) {

HelloServerDemo server= newHelloServerDemo();

server.startServer();

}

}

客户端Client代码和之前的一样,只要数据传输的协议一致即可,客户端测试成功,结果如下:

Hello World,Hello Thrift!!! Hi:Neo

TNonblockingServer 服务模型

使用非阻塞式IO,服务端和客户端需要指定 TFramedTransport 数据传输的方式。

编写服务端代码:HelloServerDemo.java

packagecom.thrift.demo.server;importorg.apache.thrift.TProcessor;importorg.apache.thrift.protocol.TCompactProtocol;importorg.apache.thrift.server.TNonblockingServer;importorg.apache.thrift.server.TServer;importorg.apache.thrift.transport.TFramedTransport;importorg.apache.thrift.transport.TNonblockingServerSocket;importcom.thrift.demo.service.HelloWorldService;importcom.thrift.demo.service.impl.HelloWorldServiceImpl;/**************************************************************

* @类名 HelloServerDemo

*

* @AUTHOR Neo

*************************************************************/

public classHelloServerDemo {public static final int SERVER_PORT = 8191;public voidstartServer() {try{

System.out.println("HelloWorld TNonblockingServer start ....");

TProcessor tprocessor= new HelloWorldService.Processor(newHelloWorldServiceImpl());

TNonblockingServerSocket tnbSocketTransport= newTNonblockingServerSocket(SERVER_PORT);

TNonblockingServer.Args tnbArgs= newTNonblockingServer.Args(tnbSocketTransport);

tnbArgs.processor(tprocessor);

tnbArgs.transportFactory(newTFramedTransport.Factory());

tnbArgs.protocolFactory(newTCompactProtocol.Factory());//使用非阻塞式IO,服务端和客户端需要指定TFramedTransport数据传输的方式

TServer server = newTNonblockingServer(tnbArgs);

server.serve();

}catch(Exception e) {

System.out.println("Server start error!!!");

e.printStackTrace();

}

}public static voidmain(String[] args) {

HelloServerDemo server= newHelloServerDemo();

server.startServer();

}

}

编写客户端代码:HelloClientDemo.java

packagecom.thrift.demo.client;importorg.apache.thrift.TException;importorg.apache.thrift.protocol.TCompactProtocol;importorg.apache.thrift.protocol.TProtocol;importorg.apache.thrift.transport.TFramedTransport;importorg.apache.thrift.transport.TSocket;importorg.apache.thrift.transport.TTransport;importorg.apache.thrift.transport.TTransportException;importcom.thrift.demo.service.HelloWorldService;/**************************************************************

* @类名 HelloClientDemo

*

* @AUTHOR Neo

*************************************************************/

public classHelloClientDemo {public static final String SERVER_IP = "127.0.0.1";public static final int SERVER_PORT = 8191;public static final int TIMEOUT = 30000;public voidstartClient(String userName) {

TTransport transport= null;try{

transport= new TFramedTransport(newTSocket(SERVER_IP, SERVER_PORT, TIMEOUT));//协议要和服务端一致

TProtocol protocol = newTCompactProtocol(transport);

HelloWorldService.Client client= newHelloWorldService.Client(protocol);

transport.open();

String result=client.sayHello(userName);

System.out.println("Thrify client result =: " +result);

}catch(TTransportException e) {

e.printStackTrace();

}catch(TException e) {

e.printStackTrace();

}finally{if (null !=transport) {

transport.close();

}

}

}public static voidmain(String[] args) {

HelloClientDemo client= newHelloClientDemo();

client.startClient("Neo");

}

}

客户端的测试成功,结果如下:

Thrify client result =: Hello World,Hello Thrift!!! Hi:Neo

THsHaServer服务模型

半同步半异步的服务端模型,需要指定为: TFramedTransport 数据传输的方式。

编写服务端代码:HelloServerDemo.java

packagecom.thrift.demo.server;importorg.apache.thrift.TProcessor;importorg.apache.thrift.protocol.TBinaryProtocol;importorg.apache.thrift.server.THsHaServer;importorg.apache.thrift.server.TServer;importorg.apache.thrift.transport.TFramedTransport;importorg.apache.thrift.transport.TNonblockingServerSocket;importcom.thrift.demo.service.HelloWorldService;importcom.thrift.demo.service.impl.HelloWorldServiceImpl;/**************************************************************

* @类名 HelloServerDemo

*

* @AUTHOR Neo

*************************************************************/

public classHelloServerDemo {public static final int SERVER_PORT = 8191;public voidstartServer() {try{

System.out.println("HelloWorld THsHaServer start ....");

TProcessor tprocessor= new HelloWorldService.Processor(newHelloWorldServiceImpl());

TNonblockingServerSocket tnbSocketTransport= newTNonblockingServerSocket(SERVER_PORT);

THsHaServer.Args thhsArgs= newTHsHaServer.Args(tnbSocketTransport);

thhsArgs.processor(tprocessor);

thhsArgs.transportFactory(newTFramedTransport.Factory());

thhsArgs.protocolFactory(newTBinaryProtocol.Factory());//半同步半异步的服务模型

TServer server = newTHsHaServer(thhsArgs);

server.serve();

}catch(Exception e) {

System.out.println("Server start error!!!");

e.printStackTrace();

}

}public static voidmain(String[] args) {

HelloServerDemo server= newHelloServerDemo();

server.startServer();

}

}

客户端代码和上一个服务模型的Client中的类似,只要注意传输协议一致以及指定传输方式为TFramedTransport。

异步客户端

编写服务端代码:HelloServerDemo.java

packagecom.thrift.demo.client;importorg.apache.thrift.TProcessor;importorg.apache.thrift.protocol.TCompactProtocol;importorg.apache.thrift.server.TNonblockingServer;importorg.apache.thrift.server.TServer;importorg.apache.thrift.transport.TFramedTransport;importorg.apache.thrift.transport.TNonblockingServerSocket;importcom.thrift.demo.service.HelloWorldService;importcom.thrift.demo.service.impl.HelloWorldServiceImpl;/**************************************************************

* @类名 HelloServerDemo

*

* @AUTHOR Neo

*************************************************************/

public classHelloServerDemo {public static final int SERVER_PORT = 8191;public voidstartServer() {try{

System.out.println("HelloWorld TNonblockingServer start ....");

TProcessor tprocessor= new HelloWorldService.Processor(newHelloWorldServiceImpl());

TNonblockingServerSocket tnbSocketTransport= newTNonblockingServerSocket(SERVER_PORT);

TNonblockingServer.Args tnbArgs= newTNonblockingServer.Args(tnbSocketTransport);

tnbArgs.processor(tprocessor);

tnbArgs.transportFactory(newTFramedTransport.Factory());

tnbArgs.protocolFactory(newTCompactProtocol.Factory());//使用非阻塞式IO,服务端和客户端需要指定TFramedTransport数据传输的方式

TServer server = newTNonblockingServer(tnbArgs);

server.serve();

}catch(Exception e) {

System.out.println("Server start error!!!");

e.printStackTrace();

}

}public static voidmain(String[] args) {

HelloServerDemo server= newHelloServerDemo();

server.startServer();

}

}

编写客户端Client代码:HelloAsynClientDemo.java

packagecom.thrift.demo.client;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.TimeUnit;importorg.apache.thrift.TException;importorg.apache.thrift.async.AsyncMethodCallback;importorg.apache.thrift.async.TAsyncClientManager;importorg.apache.thrift.protocol.TCompactProtocol;importorg.apache.thrift.protocol.TProtocolFactory;importorg.apache.thrift.transport.TNonblockingSocket;importorg.apache.thrift.transport.TNonblockingTransport;importcom.thrift.demo.service.HelloWorldService;importcom.thrift.demo.service.HelloWorldService.AsyncClient.sayHello_call;/**************************************************************

* @类名 HelloAsynClientDemo

*

* @AUTHOR Neo

*************************************************************/

public classHelloClientDemo {public static final String SERVER_IP = "127.0.0.1";public static final int SERVER_PORT = 8191;public static final int TIMEOUT = 30000;public voidstartClient(String userName) {try{

TAsyncClientManager clientManager= newTAsyncClientManager();

TNonblockingTransport transport= newTNonblockingSocket(SERVER_IP, SERVER_PORT, TIMEOUT);

TProtocolFactory tprotocol= newTCompactProtocol.Factory();

HelloWorldService.AsyncClient asyncClient= newHelloWorldService.AsyncClient(tprotocol, clientManager, transport);

System.out.println("Client start .....");

CountDownLatch latch= new CountDownLatch(1);

AsynCallback callBack= newAsynCallback(latch);

System.out.println("call method sayHello start ...");

asyncClient.sayHello(userName, callBack);

System.out.println("call method sayHello .... end");boolean wait = latch.await(30, TimeUnit.SECONDS);

System.out.println("latch.await =:" +wait);

}catch(Exception e) {

e.printStackTrace();

}

System.out.println("startClient end.");

}public class AsynCallback implements AsyncMethodCallback{privateCountDownLatch latch;publicAsynCallback(CountDownLatch latch) {this.latch =latch;

}

@Overridepublic voidonComplete(sayHello_call response) {

System.out.println("onComplete");try{//Thread.sleep(1000L * 1);

System.out.println("AsynCall result =:" +response.getResult().toString());

}catch(TException e) {

e.printStackTrace();

}catch(Exception e) {

e.printStackTrace();

}finally{

latch.countDown();

}

}

@Overridepublic voidonError(Exception exception) {

System.out.println("onError :" +exception.getMessage());

latch.countDown();

}

}public static voidmain(String[] args) {

HelloAsynClientDemo client= newHelloAsynClientDemo();

client.startClient("Neo");

}

}

先运行服务程序,再运行客户端程序,测试结果如下:

Client start .....

call method sayHello start ...

call method sayHello .... end

onComplete

AsynCall result=:Hello World,Hello Thrift!!!Hi:Neo

latch.await=:truestartClient end.

设计思路

Thrift的Server类型有TSimpleServer、TNonblockingServer、THsHaServer、TThreadedSelectorServer、TThreadPoolServer

TSimpleServer是单线程阻塞IO的方式,仅用于demo

TNonblockingServer是单线程非阻塞IO的方式,通过java.nio.channels.Selector的select()接收连接请求,但是处理消息仍然是单线程,吞吐量有限不可用于生产

THsHaServer使用一个单独的线程处理IO,一个独立的worker线程池处理消息, 可以并行处理所有请求

TThreadPoolServer使用一个专用连接接收connection,一旦接收到请求就会放入ThreadPoolExecutor中的一个worker里处理,当请求处理完毕该worker释放并回到线程池中,可以配置线程最大值,当达到线程最大值时请求会被阻塞。TThreadPoolServer性能表现优异,代价是并发高时会创建大量线程

TThreadedSelectorServer是thrift 0.8引入的实现,处理IO也使用了线程池,比THsHaServer有更高的吞吐量和更低的时延,与TThreadPoolServer比性能相近且能应对网络IO较多的情况

对于客户端较少的情况,TThreadPoolServer也有优异的性能表现,但是考虑到未来SOA可能的高并发,决定采用TThreadedSelectorServer

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值