发一个自己用于生产环境 C++网络库

2020-04-21 05:31:39 +08:00
 wlgq2


项目地址:uv-cpp
之前发过,最近失业空闲,给这个网络库增加了 http 支持,实现了一个基于 RadixTree 的路由,可以支持通配符*,或者设置参数之类。大概可以实现这样的效果

int main(int argc, char** args)
{
    uv::EventLoop loop;
    uv::http::HttpServer::SetBufferMode(uv::GlobalConfig::BufferMode::CycleBuffer);

    uv::http::HttpServer server(&loop);
	
    //example:  127.0.0.1:10010/test
    server.Get("/test",std::bind(&func1,std::placeholders::_1,std::placeholders::_2));
    
    //example:  127.0.0.1:10010/some123abc
    server.Get("/some*",std::bind(&func2, std::placeholders::_1, std::placeholders::_2));
    
    //example:  127.0.0.1:10010/value:1234
    server.Get("/value:",std::bind(&func3, std::placeholders::_1, std::placeholders::_2));
    
    //example:  127.0.0.1:10010/sum?param1=100&param2=23
    server.Get("/sum",std::bind(&func4, std::placeholders::_1, std::placeholders::_2));
    
    uv::SocketAddr addr("127.0.0.1", 10010);
    server.bindAndListen(addr);
    loop.run();
}

顺带和 boost.asio 以及 nginx 做了性能对比


ping-pong 测试显示 uv-cpp 有不弱于 boost.asio 的并发性能,不过这主要是由于 libuv 本身很强大。



1000 并发,100000 次请求和 nginx 对比


不出意料的,单位时间请求及字节传输都不如 nginx,不过 nginx 不知道是不是我配置有问题,有 500+次失败请求,uv-cpp 没有。


接口也比较简单,10 行代码实现一个 echo 服务器

#include <iostream>
#include <uv/include/uv11.h>

int main(int argc, char** args)
{
    uv::EventLoop* loop = uv::EventLoop::DefaultLoop();
	
    uv::TcpServer server(loop);
    server.setMessageCallback([](uv::TcpConnectionPtr ptr,const char* data, ssize_t size)
    {
        ptr->write(data, size, nullptr);
    });
	
    uv::SocketAddr addr("0.0.0.0", 10005, uv::SocketAddr::Ipv4);
    server.bindAndListen(addr);
    loop->run();
}

欢迎 star 、issue 、pr……

5103 次点击
所在节点    C++
23 条回复
OneMan
2020-04-24 17:39:05 +08:00
什么 pingpong 性能之类的,没什么意义。
wlgq2
2020-05-06 20:31:26 +08:00
@OneMan 我自己用倒是挺稳定的。主要是它内核是基于 libuv,做了一层 modern cpp 的封装。而且代码就几千行,改起来也容易。如果项目本身就是基于 libuv,可以试试迁移。
OneMan
2020-05-06 22:08:14 +08:00
@wlgq2 你最近赋闲呢,在哪,要工作吗

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/664486

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX