Some time ago I was facing a challenge, making a PHP script that randomly picks a server from a server list, to create a load balancing effect. The script expects that the servers are replicated, so that only the server name need to be provided. Resulting resources would be like:
http://alpha.jeroen.pro/static/background.jpg
http://beta.jeroen.pro/static/background.jpg
Code:
PHP |copy code |?
01 <?php
02 function select_server($servers, $default)03 {
04 $server = $default;05 $gotServer = false;06 while($gotServer == false && count($servers) > 0)07 {
08 $randomkey = array_rand($servers);09 $server = $servers[$randomkey];10 $port = 80;11 12 $status = apc_fetch("server_test_".$server, &$fetchstatus);13 14 if($fetchstatus == false)15 {
16 if($fp=@fsockopen($server,$port,$ERROR_NO,$ERROR_STR,1))17 {
18 fclose($fp);19 $status = "online";20 }
21 else
22 {
23 $status = "offline";24 }
25 apc_store("server_test_".$server, $status, 10);26 }
27 28 if($status != "offline")29 {
30 $gotServer = true;31 $server = $servers[$randomkey];32 }
33 else
34 {
35 unset($servers[$randomkey]);36 unset($status);37 unset($fetchstatus);38 $server = $default;39 }
40 }
41 return $server;42 }
43 ?>
44 45
Remember: the code uses APC to store the server status for 10 seconds, you could remove the APC part, but that would cause extra load on the servers.
The code loops through the server list(which was made random), and tries every server until it found one that is online. If none is online, it’s going to the default server.
Usage:
PHP |copy code |?
1 <?php
2 $servers = array('alpha.jeroen.pro', 'beta.jeroen.pro');3 $default = "jeroen.pro";4 $server = select_server($servers, $default);5 echo '<img src="http://'.$server.'/static/background.jpg" />';6 ?>
Thanks for the share!
Nancy.R