Обработка временных сбоев: методы и примеры кода

Вот несколько способов устранения временных сбоев:

  1. Механизм повтора:
    Реализуйте механизм повтора, позволяющий автоматически повторять неудачную операцию после определенной задержки. Вот пример на Python:
import time
def handle_temporary_failure():
    max_retries = 3
    retry_delay = 5  # seconds
    for i in range(max_retries):
        try:
            # Perform the operation that may fail temporarily
            result = perform_operation()
            # If the operation succeeds, exit the loop
            return result
        except TemporaryFailureException:
            # Log the failure
            print("Temporary failure. Retrying in {} seconds...".format(retry_delay))
            # Wait for the specified delay before retrying
            time.sleep(retry_delay)
    # Operation failed after maximum retries
    print("Operation failed after maximum retries.")
    return None
  1. Экспоненциальная отсрочка.
    Реализация алгоритма экспоненциальной отсрочки, при котором задержка между повторными попытками увеличивается экспоненциально с каждой попыткой. Такой подход помогает избежать перегрузки системы во время временного сбоя. Вот пример на Java:
import java.util.Random;
public class RetryHandler {
    private static final int MAX_RETRIES = 5;
    private static final int INITIAL_DELAY_MS = 1000; // milliseconds
    public void handleTemporaryFailure() {
        int retries = 0;
        int delay = INITIAL_DELAY_MS;
        Random random = new Random();
        while (retries < MAX_RETRIES) {
            try {
                // Perform the operation that may fail temporarily
                performOperation();
                // If the operation succeeds, exit the loop
                return;
            } catch (TemporaryFailureException e) {
                // Log the failure
                System.out.println("Temporary failure. Retrying in " + delay + " milliseconds...");
                // Wait for a random delay within a range before retrying
                int randomDelay = random.nextInt(delay);
                delay *= 2;
                retries++;
                try {
                    Thread.sleep(randomDelay);
                } catch (InterruptedException ignored) {
                }
            }
        }
// Operation failed after maximum retries
        System.out.println("Operation failed after maximum retries.");
    }
}
  1. Шаблон автоматического выключателя.
    Внедрите шаблон автоматического выключателя для обнаружения и устранения временных сбоев. Автоматический выключатель контролирует интенсивность отказов и размыкает цепь, когда отказы превышают определенный порог. Вот пример на C# с использованием библиотеки Polly:
using System;
using Polly;
using Polly.CircuitBreaker;
public class CircuitBreakerExample
{
    private CircuitBreakerPolicy _circuitBreaker;
    public CircuitBreakerExample()
    {
        _circuitBreaker = Policy
            .Handle<TemporaryFailureException>()
            .CircuitBreaker(3, TimeSpan.FromMinutes(1), OnCircuitOpened, OnCircuitClosed);
    }
    public void HandleTemporaryFailure()
    {
        _circuitBreaker.Execute(PerformOperation);
    }
    private void PerformOperation()
    {
        // Perform the operation that may fail temporarily
    }
    private void OnCircuitOpened()
    {
        Console.WriteLine("Circuit breaker opened. Operation temporarily unavailable.");
    }
    private void OnCircuitClosed()
    {
        Console.WriteLine("Circuit breaker closed. Operation available again.");
    }
}