HttpRequester支持失败重试功能(#2323)

This commit is contained in:
mtdxc 2023-03-23 14:46:45 +08:00 committed by GitHub
parent dfd37ff350
commit 98ec6b68d9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 1 deletions

View File

@ -11,7 +11,7 @@
#include "HttpRequester.h"
#include "Util/onceToken.h"
#include "Util/NoticeCenter.h"
#include <memory>
using namespace std;
using namespace toolkit;
@ -26,6 +26,17 @@ void HttpRequester::onResponseBody(const char *buf, size_t size) {
}
void HttpRequester::onResponseCompleted(const SockException &ex) {
if (ex && _retry++ < _max_retry) {
std::weak_ptr<HttpRequester> weak_self = std::dynamic_pointer_cast<HttpRequester>(shared_from_this());
getPoller()->doDelayTask(_retry_delay, [weak_self](){
if (auto self = weak_self.lock()) {
InfoL << "resend request " << self->getUrl() << " with retry " << self->getRetry();
self->sendRequest(self->getUrl());
}
return 0;
});
return ;
}
const_cast<Parser &>(response()).setContent(std::move(_res_body));
if (_on_result) {
_on_result(ex, response());
@ -33,8 +44,15 @@ void HttpRequester::onResponseCompleted(const SockException &ex) {
}
}
void HttpRequester::setRetry(size_t count, size_t delay) {
InfoL << "setRetry max=" << count << ", delay=" << delay;
_max_retry = count;
_retry_delay = delay;
}
void HttpRequester::startRequester(const string &url, const HttpRequesterResult &on_result, float timeout_sec) {
_on_result = on_result;
_retry = 0;
setCompleteTimeout(timeout_sec * 1000);
sendRequest(url);
}

View File

@ -25,6 +25,10 @@ public:
void setOnResult(const HttpRequesterResult &onResult);
void startRequester(const std::string &url, const HttpRequesterResult &on_result, float timeout_sec = 10);
void setRetry(size_t count, size_t delay);
size_t getRetry() const { return _retry; }
size_t getRetryDelay() const { return _retry_delay; }
size_t getMaxRetry() const { return _max_retry; }
void clear() override;
private:
@ -33,6 +37,9 @@ private:
void onResponseCompleted(const toolkit::SockException &ex) override;
private:
size_t _retry = 0;
size_t _max_retry = 0;
size_t _retry_delay = 2000; // ms
std::string _res_body;
HttpRequesterResult _on_result;
};