The company's system has no fault-tolerant mechanism at all. So I think of java microservices.
First, you need a registry getService.php
<?php $array = ["produce" => [ ["url" => "http://127.0.0.1/testSwitch/producer1.php","status" => "1"], ["url" => "http://127.0.0.1/testSwitch/producer2.php","status" => "-1"], ["url" => "http://127.0.0.1/testSwitch/producer3.php","status" => "-1"], ] ]; echo json_encode($array); ?>
Three service providers are represented by status.
<?php //Used to test timeout mechanism //sleep(120); echo "producer1"; ?>
Consumer, caller of the service.
There are mainly three steps. The first step is to get the service that can be invoked. The second step is to select a service. The third step is to invoke the service.
If there is a problem in the service, the registry can be notified to modify the status of the current service, and the operation and maintenance personnel can be notified by SMS at the same time. This ensures that the next call is normal.
<?php function chooseUrl($urls){ //Or exceptional capture $url = null; foreach($urls as $u){ if($u['status'] == -1){ continue; }else{ $url = $u['url']; } } return $url; } function getContent($url){ //Or exceptional capture //Timeout mechanism $ctx = stream_context_create(array('http'=> array( 'timeout' => 10, ) )); $content = file_get_contents($url,false,$ctx); return empty($content) ? false : $content; } function getServices($serviceName){ //Or exceptional capture $services = file_get_contents('http://127.0.0.1/testSwitch/getService.php'); if(empty($services)){ return false; } $services = json_decode($services,true); $urls = $services[$serviceName]; return empty($urls) ? false : $urls; } function run($serviceName){ $urls = getServices($serviceName); if(!$urls){ //Registry error, maybe exception return false; } $url = chooseUrl($urls); if(empty($url)){ //No service available, maybe exception return false; } $content = getContent($url); if(empty($content)){ //Service error, update service information. echo $url." Service error "; return false; } return $content; } $result = run("produce"); if(!$result){ echo "Default fusing mechanism"; }else{ echo $result; } ?>
Test 1
Result
Here is how to manually modify the registry status
Result
Unannotate producer for timeout testing
Other factors on the server result in service timeouts. In this way, state changes can also be made.