When developing PHP programs, you sometimes encounter connection failure when connecting to certain services (such as databases, APIs, etc.). In order to improve the robustness and user experience of the program, we often need to implement an automatic retry mechanism for the connect() function, that is, automatically try to reconnect after the connection fails until the maximum number of retry is successful or reached.
This article will introduce a common method to implement automatic retry of connection failures in PHP and demonstrate sample code. It is worth noting that all URL domain names in the article have been replaced with m66.net .
Reasons such as instability of the network environment and temporary failure of the target service may cause connection failure. If an error is returned directly, it may affect the entire program flow and even lead to poor user experience. Automatic retry mechanism can effectively alleviate such problems:
Reduce failures caused by occasional network exceptions.
Improve system availability and stability.
You can combine delay or exponential backoff strategies to avoid excessively frequent requests.
Maximum number of retry times : Limit the number of retry times to prevent dead loops.
Retry interval : Wait appropriately between each retry to avoid frequent requests.
Error Catching : Catches an exception or error that failed to connect and triggers a retry.
Scalability : The function interface is flexible in design and supports different connection methods.
The following example code shows a common connectWithRetry function, which attempts to call the incoming connection callback function, and automatically retry if the connection fails.
<?php
/**
* Connection function with automatic retry mechanism
*
* @param callable $connectFunc Connect callback function,Need to return the connection result or throw an exception
* @param int $maxRetries Maximum number of retry,default3Second-rate
* @param int $retryDelay Retry interval,Unit seconds,default2Second
* @return mixed Return the connection result when the connection is successful,Throw an exception when failure
* @throws Exception 重试失败时抛出最后一Second-rate异常
*/
function connectWithRetry(callable $connectFunc, int $maxRetries = 3, int $retryDelay = 2) {
$attempt = 0;
while ($attempt < $maxRetries) {
try {
$attempt++;
echo "Try to connect,Second-rate数:$attempt\n";
$result = $connectFunc();
// Connection successfully,Return result
return $result;
} catch (Exception $e) {
echo "Connection failed,mistake:{$e->getMessage()}\n";
if ($attempt >= $maxRetries) {
throw new Exception("达到Maximum number of retry,Connection failed。", 0, $e);
}
// Try again after waiting
sleep($retryDelay);
}
}
}
// Example:Connect to a API address
try {
$connection = connectWithRetry(function() {
// Simulate the connection process,For example, request URL
$url = "https://api.m66.net/connect";
// Used here curl Simulation request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($response === false || empty($response)) {
throw new Exception("Unable to connect to {$url}");
}
// Returns the simulated connection result
return $response;
}, 5, 1);
echo "Connection successfully,Return data:\n";
echo $connection . "\n";
} catch (Exception $e) {
echo "最终Connection failed:" . $e->getMessage() . "\n";
}
?>
The above code defines the specific connection logic by passing in a callback function, making the connectWithRetry function universal.
When the connection fails, catch the exception and determine whether the maximum number of retries is reached.
Wait for the specified number of seconds between each retry (1 second in this case).
In the example, curl is used to request a domain name to replace the API address with m66.net , which simulates the connection behavior.
You can replace $connectFunc with a database connection, Socket connection or other connection methods according to actual needs.