不知道你是什么意思的异步客户端,但我会尽我所能根据我的理解回答这个问题。
如果通过“异步客户端”,您的意思是像node.js中那样讨论异步,其中执行遵循回调结构,AFAIK不是开源节点的一部分。但是,在fbthrift
中可用。 Facebook有很多工具可以与fbthrift
一起使用,包括他们流行的开源C++库folly
。通过节俭的C++客户端接口调用其他节俭服务必须阻止。
这是我开始使用async非阻塞服务器时的代码。希望它有帮助!
something.thrift
#!/usr/local/bin/thrift --gen cpp
namespace cpp something
service Something {
i32 ping()
}
SomethingServer.cpp
#include "gen-cpp/Something.h"
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/server/TSimpleServer.h>
#include <thrift/server/TThreadedServer.h>
#include <thrift/server/TNonblockingServer.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/concurrency/ThreadManager.h>
#include <iostream>
using std::cout;
using std::endl;
class SomethingHandler : virtual public something::SomethingIf {
public:
SomethingHandler() {
cout << "Initialized" << endl;
}
int32_t ping() override {
// Your implementation goes here
cout << "Ping!" << endl;
return 1;
}
};
int main(int argc, char **argv) {
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::apache::thrift::concurrency;
using boost::shared_ptr;
using namespace ::something;
int port = 9090;
shared_ptr<SomethingHandler> handler(new SomethingHandler());
shared_ptr<TProcessor> processor(new SomethingProcessor(handler));
shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
// using thread pool with maximum 15 threads to handle incoming requests
shared_ptr<ThreadManager> threadManager
= ThreadManager::newSimpleThreadManager(15);
shared_ptr<PosixThreadFactory> threadFactory
= shared_ptr<PosixThreadFactory>(new PosixThreadFactory());
threadManager->threadFactory(threadFactory);
threadManager->start();
TNonblockingServer server(processor, protocolFactory, port, threadManager);
server.serve();
return 0;
}
SomethingClient.cpp
#include "Something.h"
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace Test;
int main(int /* argc */, char** /* argv */) {
boost::shared_ptr<TSocket> socket(new TSocket("localhost", 9090));
boost::shared_ptr<TTransport> transport(new TFramedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
SomethingClient client(protocol);
transport->open();
for (auto i = 0; i < 10000; ++i) {
client.ping();
}
transport->close();
return 0;
}
我很高兴地看到,这段代码。这正是我所寻找的例子,因为它似乎不是来自“fbthrift”,而且也不依赖于我们希望避免的软件包(比如“愚蠢”)。 今天晚上我会试一试这个例子,但我想花时间来感谢你! 稍后更多信息... –
进一步阅读后,您的示例代码似乎没有实现任何形式的回调。 我想你想告诉我,我真的必须使用fbthrift成功创建一个客户端调用,该服务在服务器完成任务时立即返回,并与回调机制一起使用。 这是你的理解吗? –
@GordonFossum是的,这就是我从它和我看到的节俭问题。 fbthrift使用愚蠢的期货和回调支持来启用基于回调的处理。升压期货确实有这种情况,但我认为任何人都没有在开源节流中实现这一点。 – Curious