首页 > 解决方案 > 在 C++ 中缓存图像。使用 buffer_body 或其他东西而不是 file_body?

问题描述

我稍微修改了这个https://www.boost.org/doc/libs/develop/libs/beast/example/http/server/async/http_server_async.cpp的版本。

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

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

我试过的:

  1. 我想使用 buffer_body 而不是 file_body 但是响应部分出现了一些困难,所以我放弃了这个想法。
  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++11cachingboost

解决方案


有时不需要缓存这些文件,例如,在我的情况下,将 file_body 更改为 vector_body 或 string_body 足以加快响应时间几乎两倍


推荐阅读