c++ - 在 C++ 中缓存图像。使用 buffer_body 或其他东西而不是 file_body?
问题描述
我稍微修改了这个https://www.boost.org/doc/libs/develop/libs/beast/example/http/server/async/http_server_async.cpp的版本。
它的作用: 根据请求的正确性,它返回所需的图像或错误。
我要做什么: 我想像 LRU 缓存一样在本地缓存中保持频繁请求图像以减少响应时间
我试过的:
- 我想使用 buffer_body 而不是 file_body 但是响应部分出现了一些困难,所以我放弃了这个想法。
- 我试图将 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
}
任何帮助将不胜感激!谢谢你!
解决方案
有时不需要缓存这些文件,例如,在我的情况下,将 file_body 更改为 vector_body 或 string_body 足以加快响应时间几乎两倍
推荐阅读
- java - 如何在 Vaadin 14 中编写视频通话应用程序
- r - 使用带有字符名称的变量的饼图
- image - 以前有什么建议让颤振应用程序中的背景图像与所有屏幕兼容吗?
- json - ng 重复嵌套循环
- r - Python - Pyomo - R - Reticulate - [WinError 6] 句柄无效
- mobile - 在移动Safari中,单击选择输入时,页面内容在第一次单击时闪烁
- css - CSS Grid 使列间距相同
- c# - 解析Excel电子表格的单元格值
- javascript - 如何从javascript中的嵌套对象数组中删除特定项目属性
- django - 如何重定向到 django 中的绝对 url 路径?