您的位置:首页 > 编程语言 > C语言/C++

Thrift C++ 多路复用可实现多个Service

2016-01-25 00:00 274 查看

介绍

Thrift作为一个跨语言的rpc框架,为后端服务间的多语言混合开发提供了高可靠,可扩展,以及高效的实现。但是自从2007年facebook开源后的6年时间内一直缺少一个多路复用的功能(Multiplexing Services),也就是在一个Server上面实现多个Service调用。比如要实现一个后端服务,很多时候不仅仅只是实现业务服务接口,往往还会预留一些调试,监控服务接口,以往要实现多个Service在一个Server上面调用,要么将多个服务糅合成一个庞大的服务(图1),要么将多个Service分摊到不同的Server上(图2)。最近的版本0.9.1终于实现内置的多路复用,本文将就该功能简要分析一下该功能的设计与实现,并提供一个简单的示例。



图1



图2

实现

新增代码

protocol/TMultiplexedProtocol.h

protocol/TMultiplexedProtocol.cpp

protocol/TProtocolDecorator.h

processor/TMultiplexedProcessor.h

使用示例

IDL

namespace cpp thrift.multiplex.demo

service FirstService
{
void blahBlah()
}

service SecondService
{
void blahBlah()
}

Server:

int port = 9090;
shared_ptr<TProcessor> processor1(new FirstServiceProcessor
(shared_ptr<FirstServiceHandler>(new FirstServiceHandler())));
shared_ptr<TProcessor> processor2(new SecondServiceProcessor
(shared_ptr<SecondServiceHandler>(new SecondServiceHandler())));

//使用MultiplexedProcessor
shared_ptr<TMultiplexedProcessor> processor(new TMultiplexedProcessor());

//注册各自的Service
processor->registerProcessor("FirstService", processor1);
processor->registerProcessor("SecondService", processor2);

shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
server.serve();

Client:

int port = 9090;
shared_ptr<TProcessor> processor1(new FirstServiceProcessor
(shared_ptr<FirstServiceHandler>(new FirstServiceHandler())));

shared_ptr<TProcessor> processor2(new SecondServiceProcessor
(shared_ptr<SecondServiceHandler>(new SecondServiceHandler())));

//使用MultiplexedProcessor
shared_ptr<TMultiplexedProcessor> processor(new TMultiplexedProcessor());

//注册各自的Service
processor->registerProcessor("FirstService", processor1);
processor->registerProcessor("SecondService", processor2);

shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
server.serve();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: