【发布时间】:2021-08-30 22:41:45
【问题描述】:
我对这个 https://www.boost.org/doc/libs/develop/libs/beast/example/http/server/async/http_server_async.cpp 做了一些修改。
它的作用: 根据请求的正确性返回所需的图像或错误。
我要做什么: 我想像 LRU 缓存一样在本地缓存中保持频繁请求图像以减少响应时间
我的尝试:
- 我想用buffer_body代替file_body,但是response部分出现了一些问题,所以我放弃了这个想法。
- 我尝试将 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
}
我们将不胜感激任何帮助!谢谢!
【问题讨论】:
-
请出示minimal reproducible example您遇到了什么问题?
-
系统对最近使用的文件进行了缓冲缓存,以加快读取速度,优化后可能如您所料有明显提升。stackify.com/premature-optimization-evil/…。