From 98ec6b68d99397f0fcbf78d61c7aca0de32081e2 Mon Sep 17 00:00:00 2001 From: mtdxc Date: Thu, 23 Mar 2023 14:46:45 +0800 Subject: [PATCH] =?UTF-8?q?HttpRequester=E6=94=AF=E6=8C=81=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E9=87=8D=E8=AF=95=E5=8A=9F=E8=83=BD(#2323)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Http/HttpRequester.cpp | 20 +++++++++++++++++++- src/Http/HttpRequester.h | 7 +++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Http/HttpRequester.cpp b/src/Http/HttpRequester.cpp index e6e91378..669d17fe 100644 --- a/src/Http/HttpRequester.cpp +++ b/src/Http/HttpRequester.cpp @@ -11,7 +11,7 @@ #include "HttpRequester.h" #include "Util/onceToken.h" #include "Util/NoticeCenter.h" - +#include 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 weak_self = std::dynamic_pointer_cast(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(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); } diff --git a/src/Http/HttpRequester.h b/src/Http/HttpRequester.h index 69dd05a6..067bb0e8 100644 --- a/src/Http/HttpRequester.h +++ b/src/Http/HttpRequester.h @@ -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; };