#include <iostream>
#include <functional>
#include <chrono>
#include <thread>
template <typename ReturnType>
class RetryPolicy {
public:
enum class DelayStrategy { FIXED, EXPONENTIAL, MULTIPLICATIVE };
RetryPolicy(int maxRetries, std::function<ReturnType()> func, std::function<bool(ReturnType)> retryCondition, std::function<void()> onMaxRetriesReached, DelayStrategy strategy, int onceWaitTime)
: maxRetries(maxRetries), func(func), retryCondition(retryCondition), onMaxRetriesReached(onMaxRetriesReached), delayStrategy(strategy), onceWaitTime(onceWaitTime) {}
void executeWithRetry() {
int retries = 0;
while (retries < maxRetries) {
ReturnType result = func();
if (retryCondition(result)) {
return;
}
std::this_thread::sleep_for(std::chrono::seconds(getDelay(retries)));
retries++;
}
onMaxRetriesReached();
}
private:
int maxRetries;
int onceWaitTime;
std::function<ReturnType()> func;
std::function<bool(ReturnType)> retryCondition;
std::function<void()> onMaxRetriesReached;
DelayStrategy delayStrategy;
int getDelay(int attempt) {
switch (delayStrategy) {
case DelayStrategy::FIXED:
return onceWaitTime; // 固定时长策略
case DelayStrategy::EXPONENTIAL:
return onceWaitTime * (1 << attempt); // 指数增长策略
case DelayStrategy::MULTIPLICATIVE:
return onceWaitTime * (attempt + 1); // 固定倍数增长策略
default:
return 0;
}
}
};
int performOperation() {
// 模拟执行的操作
static int attempts = 0;
std::cout << "Performing operation... Attempt " << attempts + 1 << std::endl;
attempts++;
if (attempts < 3) {
std::cout << "Operation failed." << std::endl;
return 0; // 模拟失败情况
} else {
std::cout << "Operation succeeded." << std::endl;
return 1; // 模拟成功情况
}
}
int main() {
// 定义重试策略
RetryPolicy<int> retry(5, performOperation, [](int result) { return result != 0; }, []{ std::cout << "Max retries reached." << std::endl; }, RetryPolicy<int>::DelayStrategy::EXPONENTIAL);
// 执行操作的重试
retry.executeWithRetry();
return 0;
}
运行结果
No comments yet.