【问题标题】:Caching images in c++. Using buffer_body or other things instead of file_body?在 C++ 中缓存图像。使用 buffer_body 或其他东西而不是 file_body?
【发布时间】:2021-08-30 22:41:45
【问题描述】:

我对这个 https://www.boost.org/doc/libs/develop/libs/beast/example/http/server/async/http_server_async.cpp 做了一些修改。

它的作用: 根据请求的正确性返回所需的图像或错误。

我要做什么: 我想像 LRU 缓存一样在本地缓存中保持频繁请求图像以减少响应时间

我的尝试:

  1. 我想用buffer_body代替file_body,但是response部分出现了一些问题,所以我放弃了这个想法。
  2. 我尝试将 png 图像解码为 std::string,我认为这样可以更轻松地将其保存在 std::unordered_map 中,但代码的响应部分再次出现问题

这是响应部分:

http::response<http::file_body> res {                  
    std::piecewise_construct,                          
    std::make_tuple(std::move(body)),                  
    std::make_tuple(http::status::ok, req.version()) };
res.set(http::field::content_type, "image/png");       
res.content_length(size);                              
res.keep_alive(req.keep_alive());                      
                                                       
return send(std::move(res));

如果可以通过将图像编码和解码为字符串来做到这一点,我会在我将其读取到字符串的代码下方提供:

std::unordered_map<std::string, std::string> cache;

std::string load_file_contents(const std::string& filepath)
{
    static const size_t MAX_LOAD_DATA_SIZE = 1024 * 1024 * 8 ; // 8 Mbytes.
    std::string result;
    static const size_t BUFF_SIZE = 8192; // 8 Kbytes
    char buf[BUFF_SIZE];
    FILE* file = fopen( filepath.c_str(), "rb" ) ;

    if ( file != NULL )
    {
        size_t n;
        while( result.size() < MAX_LOAD_DATA_SIZE )
        {
            n = fread( buf, sizeof(char), BUFF_SIZE, file);
            if (n == 0)
                break;

            result.append(buf, n);
        }
        fclose(file);

    }
    return result;
}

template<class Body, class Allocator, class Send>
void handle_request(
    beast::string_view doc_root,
    http::request<Body, http::basic_fields<Allocator>>&& req,
    Send&& send)
{
.... // skipping this part not to paste all the code

    if(cache.find(path) == cache.end())
    {
        // if not in cache
        std::ifstream image(path.c_str(), std::ios::binary);
        // not in the cache and could open, so get it and decode it as a binary file
        cache.emplace(path, load_file_contents(path));
    }
.... // repsonse part (provided above) response should take from cache
}

我们将不胜感激任何帮助!谢谢!

【问题讨论】:

标签: c++ c++11 caching boost


【解决方案1】:

有时不需要缓存这些文件,例如,在我的例子中,将 file_body 更改为 vector_body 或 string_body 就足以将响应时间加快近两倍

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多