Optimize files caching

This commit is contained in:
antao 2018-10-15 15:58:11 +08:00
parent 944c981393
commit 4ac5544a54
2 changed files with 51 additions and 34 deletions

View File

@ -87,7 +87,7 @@
"use_sendfile": true, "use_sendfile": true,
//use_gzip:true by default,use gzip to compress the response body's content; //use_gzip:true by default,use gzip to compress the response body's content;
"use_gzip": true, "use_gzip": true,
//static_files_cache_time:5 by default,the time in which static file response is cached, //static_files_cache_time:5 (seconds) by default,the time in which static file response is cached,
//0 means cache forever,the negative value means no cache //0 means cache forever,the negative value means no cache
"static_files_cache_time":5 "static_files_cache_time":5
} }

View File

@ -710,11 +710,39 @@ void HttpAppFrameworkImpl::onAsyncRequest(const HttpRequestPtr &req, const std::
LOG_INFO << "file query!"; LOG_INFO << "file query!";
std::string filePath = _rootPath + path; std::string filePath = _rootPath + path;
std::shared_ptr<HttpResponseImpl> resp = std::make_shared<HttpResponseImpl>(); std::shared_ptr<HttpResponseImpl> resp = std::make_shared<HttpResponseImpl>();
//find cached response
HttpResponsePtr cachedResp;
{
std::lock_guard<std::mutex> guard(_staticFilesCacheMutex);
if (_staticFilesCache.find(filePath) != _staticFilesCache.end())
{
cachedResp = _staticFilesCache[filePath].lock();
if (!cachedResp)
{
_staticFilesCache.erase(filePath);
}
}
}
//check last modified time,rfc2616-14.25 //check last modified time,rfc2616-14.25
//If-Modified-Since: Mon, 15 Oct 2018 06:26:33 GMT //If-Modified-Since: Mon, 15 Oct 2018 06:26:33 GMT
if (_enableLastModify) if (_enableLastModify)
{
if (cachedResp)
{
if (cachedResp->getHeader("Last-Modified") == req->getHeader("If-Modified-Since"))
{
resp->setStatusCode(HttpResponse::k304NotModified);
if (needSetJsessionid)
{
resp->addCookie("JSESSIONID", session_id);
}
callback(resp);
return;
}
}
else
{ {
struct stat fileStat; struct stat fileStat;
LOG_TRACE << "enabled LastModify"; LOG_TRACE << "enabled LastModify";
@ -743,19 +771,8 @@ void HttpAppFrameworkImpl::onAsyncRequest(const HttpRequestPtr &req, const std::
resp->addHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT"); resp->addHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
} }
} }
//find cached response
HttpResponsePtr cachedResp;
{
std::lock_guard<std::mutex> guard(_staticFilesCacheMutex);
if (_staticFilesCache.find(filePath) != _staticFilesCache.end())
{
cachedResp = _staticFilesCache[filePath].lock();
if (!cachedResp)
{
_staticFilesCache.erase(filePath);
}
}
} }
if (cachedResp) if (cachedResp)
{ {
if (needSetJsessionid) if (needSetJsessionid)