发布一个高性能的Reactor模式的C++网络库:evpp
发布一个高性能的Reactor模式的C++网络库:evpp简介https://github.com/Qihoo360/evpp是一个基于libevent开发的现代化的支持C++11特性的高性能网络库,自带TCP/UDP/HTTP等协议的异步非阻塞式的服务器和客户端库。 特性
除此之外,基于该库之上,还提供两个附带的应用层协议库:
将来还会推出 项目由来我们开发小组负责的业务需要用到TCP协议来建设长连接网关服务和一些其他的一些基于TCP的短连接服务,在调研开源项目的过程中,没有发现一个合适的库来满足我们要求。结合我们自身的业务情况,理想中的C++网络库应具备一下几个特性:
基于这些需求,可供选择的不多,所以我们只能自己开发一个。开发过程中,接口设计方面基本上大部分是参考muduo项目来设计和实现的,当然也做了一些取舍和增改;同时也大量借鉴了Golang的一些设计哲学和思想。下面举几个小例子来说明一下:
另外,我们实现过程中极其重视线程安全问题,一个事件相关的资源必须在其所属的 吞吐量Benchmark测试报告本文用 ping pong 测试来对比evpp与libevent、boost.asio、muduo] 等网络的吞吐量,测试结果表明evpp吞吐量与boost.asio、muduo等相当,比libevent高17%~130%左右。 evpp本身是基于libevent实现的,不过evpp只是用了libevent的事件循环,并没有用libevent的 性能测试相关的代码都在这里:https://github.com/Qihoo360/evpp/tree/master/benchmark/. 测试对象
系统环境
几个简单的示例代码TCP Echo服务器#include <evpp/tcp_server.h>
#include <evpp/buffer.h>
#include <evpp/tcp_conn.h>
int main(int argc,char* argv[]) {
std::string addr = "0.0.0.0:9099";
int thread_num = 4;
evpp::EventLoop loop;
evpp::TCPServer server(&loop,addr,"TCPEchoServer",thread_num);
server.SetMessageCallback([](const evpp::TCPConnPtr& conn,evpp::Buffer* msg,evpp::Timestamp ts) {
conn->Send(msg);
});
server.SetConnectionCallback([](const evpp::TCPConnPtr& conn) {
if (conn->IsConnected()) {
LOG_INFO << "A new connection from " << conn->remote_addr();
} else {
LOG_INFO << "Lost the connection from " << conn->remote_addr();
}
});
server.Init();
server.Start();
loop.Run();
return 0;
}
HTTP Echo服务器#include <evpp/exp.h>
#include <evpp/http/http_server.h>
int main(int argc,char* argv[]) {
std::vector<int> ports = { 9009,23456,23457 };
int thread_num = 2;
evpp::http::Server server(thread_num);
server.RegisterHandler("/echo",[](evpp::EventLoop* loop,const evpp::http::ContextPtr& ctx,const evpp::http::HTTPSendResponseCallback& cb) {
cb(ctx->body().ToString()); }
);
server.Init(ports);
server.Start();
while (!server.IsStopped()) {
usleep(1);
}
return 0;
}
UDP Echo服务器#include <evpp/exp.h>
#include <evpp/udp/udp_server.h>
#include <evpp/udp/udp_message.h>
int main(int argc,char* argv[]) {
std::vector<int> ports = { 1053,5353 };
evpp::udp::Server server;
server.SetMessageHandler([](evpp::EventLoop* loop,evpp::udp::MessagePtr& msg) {
evpp::udp::SendMessage(msg);
});
server.Init(ports);
server.Start();
while (!server.IsStopped()) {
usleep(1);
}
return 0;
}
致谢
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |