提高批量请求的野兽内存使用率

2024-05-08

我运行这个boost-beast-客户端-异步-ssl http://www.boost.org/doc/libs/develop/libs/beast/example/http/client/async-ssl/http_client_async_ssl.cpp例如,就可以了。但是,如果我同时创建 10000 个会话,我的程序内存使用量将增加到 400 MB 并且永远不会下降。我在没有 ssl(简单 http)的情况下进行测试,并且没有增长内存。

问:openssl 有什么问题?

有我的main功能。

    //up boost-beast-client-async-ssl session code.   
    struct io_context_runner
    {
        boost::asio::io_context * ioc;
        void operator()()const
        {
            try{
                boost::asio::io_context::work w(*ioc);
                ioc->run();
            }catch(std::exception& e){
                fprintf(stderr, "e: %s\n", e.what());
            }
        }
    };

int main(int argc, char* argv[] ){

    try
    {
        int total_run = 1;
        if (argc > 1) total_run = atoi(argv[1]);

        const char* const host = "104.236.162.70" ;// IP of  isocpp.org
        const char* const port =  "443";  // 
        const char* const target= "/" ; //

        std::string const body = ""; //
        int version =  11;

        // The io_context is required for all I/O
        boost::asio::io_context ioc;

        // The SSL context is required, and holds certificates
        ssl::context ctx{ssl::context::sslv23_client};

        // This holds the root certificate used for verification
        load_root_certificates(ctx);

        typedef std::shared_ptr< async_http_ssl::session > pointer;

        for(int i = 0; i < total_run; ++i){
            pointer s = std::make_shared< async_http_ssl::session >(ioc  , ctx   ) ;
            usleep( 1000000 / total_run ) ;
            s->run( host, port, target, version ) ;
        }
        // Launch the asynchronous operation
        //std::make_shared<session>(ioc, ctx)->run(host, port, target, version);

        // Run the I/O service. The call will return when
        // the get operation is complete.
        std::thread t{ io_context_runner{ &ioc } } ;

        t.join();

        // If we get here then the connection is closed gracefully
    }
    catch(std::exception const& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

       return EXIT_SUCCESS ;
}

编辑:ubuntu 14.04,boost 1.66,g++ 4.9.4。 OpenSSL 1.0.1f 2014 年 1 月 6 日。

编辑2:根据this https://stackoverflow.com/questions/36913157/boostasio-and-boostbind-functor-memory-is-never-released/37275288#37275288问题malloc_trim http://man7.org/linux/man-pages/man3/malloc_trim.3.html释放(返回操作系统)大量未使用的内存。如果 boost asio 本身支持 malloc_trim 在 unix 系统上进行 ssl 连接,那就最好了!


您改编该示例的方式存在几个问题:

  1. 工作线程使用以下命令锁定 io_servicework实例所以它永远不会完成
  2. you usleep在产生异步任务之前的一段时间,但是你从不运行任何任务首先直到循环完成...这意味着所有延迟都在开始之前完成any work.

这是我的建议:

  • 在启动异步任务之前运行服务
  • have 1 work实例锁定服务,以防服务在发布下一个 http 请求之前变得空闲
  • 不要锁work在工作线程内部

Live On Coliru

#include "example/common/root_certificates.hpp"

#include <boost/beast.hpp>
#include <boost/asio.hpp>

using tcp = boost::asio::ip::tcp;    // from <boost/asio/ip/tcp.hpp>
namespace ssl = boost::asio::ssl;    // from <boost/asio/ssl.hpp>
namespace http = boost::beast::http; // from <boost/beast/http.hpp>

//------------------------------------------------------------------------------

// Report a failure
void
fail(boost::system::error_code ec, char const* what)
{
    std::cerr << what << ": " << ec.message() << "\n";
}

// Performs an HTTP GET and prints the response
class session : public std::enable_shared_from_this<session>
{
    tcp::resolver resolver_;
    ssl::stream<tcp::socket> stream_;
    boost::beast::flat_buffer buffer_; // (Must persist between reads)
    http::request<http::empty_body> req_;
    http::response<http::string_body> res_;

public:
    // Resolver and stream require an io_context
    explicit
    session(boost::asio::io_context& ioc, ssl::context& ctx)
        : resolver_(ioc)
        , stream_(ioc, ctx)
    {
    }

    // Start the asynchronous operation
    void
    run(
        char const* host,
        char const* port,
        char const* target,
        int version)
    {
        // Set SNI Hostname (many hosts need this to handshake successfully)
        if(! SSL_set_tlsext_host_name(stream_.native_handle(), host))
        {
            boost::system::error_code ec{static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()};
            std::cerr << ec.message() << "\n";
            return;
        }

        // Set up an HTTP GET request message
        req_.version(version);
        req_.method(http::verb::get);
        req_.target(target);
        req_.set(http::field::host, host);
        req_.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);

        // Look up the domain name
        resolver_.async_resolve(
            host,
            port,
            std::bind(
                &session::on_resolve,
                shared_from_this(),
                std::placeholders::_1,
                std::placeholders::_2));
    }

    void
    on_resolve(
        boost::system::error_code ec,
        tcp::resolver::results_type results)
    {
        if(ec)
            return fail(ec, "resolve");

        // Make the connection on the IP address we get from a lookup
        boost::asio::async_connect(
            stream_.next_layer(),
            results.begin(),
            results.end(),
            std::bind(
                &session::on_connect,
                shared_from_this(),
                std::placeholders::_1));
    }

    void
    on_connect(boost::system::error_code ec)
    {
        if(ec)
            return fail(ec, "connect");

        // Perform the SSL handshake
        stream_.async_handshake(
            ssl::stream_base::client,
            std::bind(
                &session::on_handshake,
                shared_from_this(),
                std::placeholders::_1));
    }

    void
    on_handshake(boost::system::error_code ec)
    {
        if(ec)
            return fail(ec, "handshake");

        // Send the HTTP request to the remote host
        http::async_write(stream_, req_,
            std::bind(
                &session::on_write,
                shared_from_this(),
                std::placeholders::_1,
                std::placeholders::_2));
    }

    void
    on_write(
        boost::system::error_code ec,
        std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        if(ec)
            return fail(ec, "write");

        // Receive the HTTP response
        http::async_read(stream_, buffer_, res_,
            std::bind(
                &session::on_read,
                shared_from_this(),
                std::placeholders::_1,
                std::placeholders::_2));
    }

    void
    on_read(
        boost::system::error_code ec,
        std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        if(ec)
            return fail(ec, "read");

        // Write the message to standard out
        //std::cout << res_ << std::endl;

        // Gracefully close the stream
        stream_.async_shutdown(
            std::bind(
                &session::on_shutdown,
                shared_from_this(),
                std::placeholders::_1));
    }

    void
    on_shutdown(boost::system::error_code ec)
    {
        if(ec == boost::asio::error::eof)
        {
            // Rationale:
            // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
            ec.assign(0, ec.category());
        }
        if(ec)
            return fail(ec, "shutdown");

        // If we get here then the connection is closed gracefully
    }
};

//up boost-beast-client-async-ssl session code.   
struct io_context_runner
{
    boost::asio::io_context& ioc;
    void operator()()const
    {
        try{
            ioc.run();
        }catch(std::exception& e){
            fprintf(stderr, "e: %s\n", e.what());
        }
    }
};

namespace async_http_ssl {
    using ::session;
}

#include <thread>

int main(int argc, char *argv[]) {
    // The io_context is required for all I/O
    boost::asio::io_context ioc;
    std::thread t;

    try {
        // Run the I/O service. The call will return when all work is complete
        boost::asio::io_context::work w(ioc);
        t = std::thread { io_context_runner{ioc} };

        int total_run = 1;
        if (argc > 1)
            total_run = atoi(argv[1]);

#if 0
        auto host = "104.236.162.70";                   // IP of  isocpp.org
        auto port = "443";                              //
        auto target = "/";                              //
#else
        auto host = "127.0.0.1";
        auto port = "443";
        auto target = "/BBB/http_client_async_ssl.cpp";
#endif

        std::string const body = ""; //
        int version = 11;

        // The SSL context is required, and holds certificates
        ssl::context ctx{ssl::context::sslv23_client};

        // This holds the root certificate used for verification
        load_root_certificates(ctx);

        typedef std::shared_ptr<async_http_ssl::session> pointer;

        for (int i = 0; i < total_run; ++i) {
            pointer s = std::make_shared<async_http_ssl::session>(ioc, ctx);
            usleep(1000000 / total_run);
            s->run(host, port, target, version);
        }
    } catch (std::exception const &e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    if (t.joinable())
        t.join();

    // If we get here then the connections have been closed gracefully
}

在我的系统上,具有 1 个连接的内存分析:

有 100 个连接:

具有 1000 个连接:

Analysis

这是什么意思?当发送更多请求时,Beast 似乎仍然使用了越来越多的内存,对吧?

嗯,不。问题在于您启动请求的速度比完成请求的速度快。因此,内存负载增加主要是因为许多session实例在给定时间存在。一旦完成,他们将自动释放资源(由于使用shared_ptr<session>).

使请求顺序化

为了让大家明白这一点,这里有一个修改版本,它接受on_completion_会话处理程序:

std::function<void()> on_complete_;

// Resolver and stream require an io_context
template <typename Handler>
explicit
session(boost::asio::io_context& ioc, ssl::context& ctx, Handler&& handler)
    : resolver_(ioc)
    , stream_(ioc, ctx)
    , on_complete_(std::forward<Handler>(handler))
{
}

~session() {
    if (on_complete_) on_complete_();
}

现在您可以将主程序逻辑重写为异步操作chain:

struct Tester {
    boost::asio::io_context ioc;
    boost::optional<boost::asio::io_context::work> work{ioc};
    std::thread t { io_context_runner{ioc} };

    ssl::context ctx{ssl::context::sslv23_client};

    Tester() {
        load_root_certificates(ctx);
    }

    void run(int remaining = 1) {
        if (remaining <= 0)
            return;

        auto s = std::make_shared<session>(ioc, ctx, [=] { run(remaining - 1); });
        s->run("127.0.0.1", "443", "/BBB/http_client_async_ssl.cpp", 11);
    }

    ~Tester() {
        work.reset();
        if (t.joinable()) t.join();
    }
};

int main(int argc, char *argv[]) {
    Tester tester;
    tester.run(argc>1? atoi(argv[1]):1);
}

通过这个程序(Coliru 的完整代码 http://coliru.stacked-crooked.com/a/c7a43d2aae2f86eb),我们得到更稳定的结果:

  • 1 个请求:

  • 100 个请求:

  • 1000 个请求:

恢复吞吐量

嗯,这有点太保守了,发送many请求可能会变得非常慢。怎么样some并发?简单的:

int main(int argc, char *argv[]) {
    int const total      = argc>1? atoi(argv[1]) : 1;
    int const concurrent = argc>2? atoi(argv[2]) : 1;

    {
        std::vector<Tester> chains(concurrent);

        for (auto& chain : chains)
            chain.run(total / concurrent);
    }

    std::cout << "All done\n";
}

就这样!现在,我们可以有concurrent为总请求提供服务的独立执行链。查看运行时间的差异:

$ time ./sotest 1000
All done

real    0m53.295s
user    0m13.124s
sys 0m0.232s
$ time ./sotest 1000 10
All done

real    0m8.808s
user    0m8.884s
sys 0m1.096s

内存使用情况看起来仍然很健康:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

提高批量请求的野兽内存使用率 的相关文章

  • 计算 XML 中特定 XML 节点的数量

    请参阅此 XML
  • 如何捕获未发送到 stdout 的命令行文本?

    我在项目中使用 LAME 命令行 mp3 编码器 我希望能够看到某人正在使用什么版本 如果我只执行 LAME exe 而不带参数 我会得到 例如 C LAME gt LAME exe LAME 32 bits version 3 98 2
  • 代码 GetAsyncKeyState(VK_SHIFT) & 0x8000 中的这些数字是什么?它们是必不可少的吗?

    我试图在按下按键的简单动作中找到这些数字及其含义的任何逻辑解释 GetAsyncKeyState VK SHIFT 0x8000 可以使用哪些其他值来代替0x8000它们与按键有什么关系 GetAsyncKeyState 根据文档返回 如果
  • 如何判断计算机是否已重新启动?

    我曾经使用过一个命令行 SMTP 邮件程序 作为试用版的限制 它允许您在每个 Windows 会话中最多接收 10 封电子邮件 如果您重新启动计算机 您可能还会收到 10 个以上 我认为这种共享软件破坏非常巧妙 我想在我的应用程序中复制它
  • JNI 将 Char* 2D 数组传递给 JAVA 代码

    我想从 C 代码通过 JNI 层传递以下指针数组 char result MAXTEST MAXRESPONSE 12 12 8 3 29 70 5 2 42 42 在java代码中我写了以下声明 public static native
  • Visual Studio 在构建后显示假错误

    我使用的是 Visual Studio 2017 构建后 sln在调试模式下 我收到错误 但是 当我通过双击错误列表选项卡中的错误来访问错误时 错误会从页面中消失 并且错误数量也会减少 我不太确定这种行为以及为什么会发生这种情况 有超过 2
  • 从客户端访问 DomainService 中的自定义对象

    我正在使用域服务从 Silverlight 客户端的数据库中获取数据 在DomainService1 cs中 我添加了以下内容 EnableClientAccess public class Product public int produ
  • Python 属性和 Swig

    我正在尝试使用 swig 为一些 C 代码创建 python 绑定 我似乎遇到了一个问题 试图从我拥有的一些访问器函数创建 python 属性 方法如下 class Player public void entity Entity enti
  • 识别 Visual Studio 中的重载运算符 (c++)

    有没有办法使用 Visual Studio 快速直观地识别 C 中的重载运算符 在我看来 C 中的一大问题是不知道您正在使用的运算符是否已重载 Visual Studio 或某些第三方工具中是否有某些功能可以自动突出显示重载运算符或对重载运
  • 为什么从字典中获取时会得到 Action<> 的克隆?

    我有以下字典 private Dictionary
  • 在视口中查找 WPF 控件

    Updated 这可能是一个简单或复杂的问题 但在 wpf 中 我有一个列表框 我用一个填充数据模板从列表中 有没有办法找出特定的数据模板项位于视口中 即我已滚动到其位置并且可以查看 目前我连接到了 listbox ScrollChange
  • 在 NaN 情况下 to_string() 可以返回什么

    我使用 VS 2012 遇到了非常令人恼火的行为 有时我的浮点数是 NaN auto dbgHelp std to string myFloat dbgHelp最终包含5008角色 你不能发明这个东西 其中大部分为0 最终结果是 0 INF
  • 高效列出目录中的所有子目录

    请参阅迄今为止所采取的建议的编辑 我正在尝试使用 WinAPI 和 C 列出给定目录中的所有目录 文件夹 现在我的算法又慢又低效 使用 FindFirstFileEx 打开我正在搜索的文件夹 然后我查看目录中的每个文件 使用 FindNex
  • 在屏幕上获取字符

    我浏览了 NCurses 函数列表 似乎找不到返回已打印在屏幕上的字符的函数 每个字符单元格中存储的字符是否有可访问的值 如果没有的话Windows终端有类似的功能吗 我想用它来替换屏幕上某个值的所有字符 例如 所有a s 具有不同的特征
  • 在 Windows Phone silverlight 8.1 上接收 WNS 推送通知

    我有 Windows Phone 8 1 silverlight 应用程序 我想使用新框架 WNS 接收通知 我在 package appxmanifest 中有
  • 使用 C 在 OS X 中获取其他进程的 argv

    我想获得其他进程的argv 例如ps 我使用的是在 Intel 或 PowerPC 上运行的 Mac OS X 10 4 11 首先 我阅读了 ps 和 man kvm 的代码 然后编写了一些 C 代码 include
  • 为boost python编译的.so找不到模块

    我正在尝试将 C 代码包装到 python 中 只需一个类即可导出两个函数 我编译为map so 当我尝试时import map得到像噪音一样的错误 Traceback most recent call last File
  • 如何减少具有多个单元的 PdfPTable 的内存消耗

    我正在使用 ITextSharp 创建一个 PDF 它由单个 PdfTable 组成 不幸的是 对于特定的数据集 由于创建了大量 PdfPCell 我遇到了内存不足异常 我已经分析了内存使用情况 我有近百万个单元格的 1 2 在这种情况下有
  • 灵气序列解析问题

    我在使用 Spirit Qi 2 4 编写解析器时遇到一些问题 我有一系列键值对以以下格式解析
  • 不区分大小写的字符串比较 C++ [重复]

    这个问题在这里已经有答案了 我知道有一些方法可以进行忽略大小写的比较 其中涉及遍历字符串或一个good one https stackoverflow com questions 11635 case insensitive string

随机推荐

  • 整数转浮点数

    这段代码的工作原理 posToXY Float gt Float gt Integer posToXY a b do let y a b round y 但这不起作用 posToXY Integer gt Integer gt Intege
  • Pandas:根据是否为 ​​NaN 来移动列

    我有一个像这样的数据框 phone number 1 clean phone number 2 clean phone number 3 clean NaN NaN 8546987 8316589 8751369 NaN 4569874 N
  • 计算 .NET Core 项目的代码指标?

    我正在研究 ASP NET Core 和 NET Core 项目 对于经典的 C 项目 Visual Studio 2015 具有计算代码指标的功能 对于 NET Core 预览版 2 工具中缺少支持 在工具更加完整之前 有人知道解决方法吗
  • Emacs 强制组织模式捕获缓冲区在新窗口中打开

    如何强制组织模式的捕获缓冲区在新窗口中打开 我试过 setq special display regexps Capture 但它不起作用 我立即看到一个新窗口 然后 org mode 进行两个垂直分割 我使用 3 个垂直分割 并将捕获缓冲
  • Sencha-touch :保存登录名/密码(保存会话,多任务)

    我有一个 Java Web 应用程序 其中移动部分是用 Sencha touch 开发的 当我启动 sencha touch 应用程序时 她询问我的登录名 密码 因为该应用程序的访问受到限制 但是我想保存用户的登录名 密码 sencha t
  • ruby 调试和黄瓜

    我在 Cucumber 中遇到了失败的情况 我想使用 ruby debug 来调试我的 Rails 控制器 但是 如果我将 调试器 添加到我想要中断的位置 它就不会停止 我尝试将 ruby debug 和 ruby gems 的 requi
  • f# 运行总计序列

    好吧 这看起来应该很容易 但我就是不明白 如果我有一个数字序列 如何生成由运行总计组成的新序列 例如 对于序列 1 2 3 4 我想将其映射到 1 3 6 10 以适当的功能方式 Use List scan https msdn micro
  • Lua中按字符分割字符串

    我有像这样的字符串 ABC DEF 我需要将它们分开 字符并将两个部分分别分配给一个变量 在 Ruby 中 我会这样做 a b ABC DEF split 显然Lua没有这么简单的方法 经过一番挖掘后 我找不到一种简短的方法来实现我所追求的
  • 结构化 scala 案例类的自定义 json 序列化

    我有一些用于往返 scala 案例类的工作 jackson scala 模块代码 Jackson 对于平面案例类非常有用 但是当我制作一个包含其他案例类列表的案例时 我似乎需要很多代码 考虑 abstract class Message c
  • iOS UITest:如何找到UITableViewCell的AccessoryView?

    你好我正在学习UITests now 我有个问题 如何检测accessoryView的点击tableViewCell 在UI测试中 下面是我的tableViewCell 我想要检测细节闭合配件视图水龙头 像这样 app tables cel
  • 增加浏览器缩放时 mediaelement.js 音量控制混乱

    媒体元素2 12 0 这种情况仅发生在 FF 和 Chrome 中 而不会发生在 IE 或 Opera 中 导航到具有媒体元素播放器的网站内容后 甚至导航到媒体元素首页http mediaelementjs com http mediael
  • 我可以在方法体内使用注释吗?

    允许 Java 注释的语义将它们放置在某处在函数体内 例如注释特定的函数调用 语句或表达式 例如 class MyClass void theFunc Thing thing String s null Catching NullPoint
  • Mink 不适用于 behat 3.0.12

    我安装了 Behat Mink 和其他一些相关的软件包 这是我的composer json 文件 require behat behat 3 0 6 behat symfony2 extension dev master behat min
  • 当按多列分组时,如何命名 dplyr 中的 group_split 列表

    我在 dplyr 中使用 group split 在分割了多个列后 我很难命名列表 当我们按一列分组时 我知道该怎么做here https stackoverflow com questions 57107721 how to name t
  • 如何包装实体框架以在执行前拦截 LINQ 表达式?

    我想在执行之前重写 LINQ 表达式的某些部分 我在将重写器注入正确的位置时遇到问题 实际上根本没有 查看实体框架源代码 在反射器中 它最终归结为IQueryProvider Execute在 EF 中 它通过以下方式耦合到表达式Objec
  • 如何绕过警告意外的任何。指定不同的类型 @typescript-eslint/no-explicit-any

    我们有严格的零棉绒问题政策 这意味着所有错误和警告都需要修复 在我们的 React typescript 项目中面临这个 lint 错误 warning Unexpected any Specify a different type typ
  • 案例类和案例对象之间的区别?

    我正在学习 Scala 和 Akka 并且在最近的查找中solution https stackoverflow com questions 22770927 waiting for multiple results in akka 我发现
  • Bootstrap 轮播中的 Href

    我一直在Interwebz上搜索 但似乎找不到答案 如何在轮播链接中添加 href 我尝试将 a 标签放在 h1 标签之外 但它破坏了滑块本身的功能 这是我的代码 div class col sm 12 div class carousel
  • 如何在sql中查询xml列

    我在 SQL Server 2008 上有一个表 T1 其中包含一个 XML 列 EventXML 我想查询某个节点包含特定值的所有行 更好的是 我想检索不同节点中的值 表T1 T1 EventID int EventTime dateti
  • 提高批量请求的野兽内存使用率

    我运行这个boost beast 客户端 异步 ssl http www boost org doc libs develop libs beast example http client async ssl http client asy