How To Split Randomly But Unevenly – PHP Code For Load UNBalancing

No More Random

It his article, Tom mentioned md5(), which hashes the numbers. This is a nice fast way of getting a similar effect as mt_rand(), as long as we make sure to scale it within range, so

$x=mt_rand(0,array_sum($server)-1);

becomes

$seed='something or other';
$x=hexdec(substr(md5($seed),0,8))%(array_sum($server));

(I use the substr() to limit the input to 8 hex characters – more than that and hexdec() will convert to float, an extra step not really needed here).

The value is now repeatable for any given $seed value. However, we’ve just offloaded the work – now we need a $seed that is random and evenly distributed, which is what our mt_rand() was doing for us before!

One advantage however, is that if we relate it to a repeatable value (say IP addresses), then the same IP address will get the same server – so this helps with repeatability, at least until we change the number of servers!

Keeping The Server Information Handy

We can use the array to store server details in one place for convenience:

$server=array(
  array('name'=>'alpha','load'=>10),
  array('name'=>'beta','load'=>50),
  array('name'=>'gamma','load'=>20) );

But then the call array_sum($server) won’t work – so for speed I’d recommend parallel arrays:

// info on servers
$serverInfo=array(
  array('name'=>'alpha'),
  array('name'=>'beta'),
  array('name'=>'gamma') );
// our ratio list separated for speed
$server=array(10,50,20);
SOME ITEMS YOU MIGHT ENJOY
UNO R3 Starter Kit 4 Relay for Arduino
$19.95
End Date: Friday Jan-12-2018 17:06:08 PST
Buy It Now for only: $19.95
Buy It Now | Add to watch list
Sanguino / Arduino Development Board for ATMega1284P / ATMega644P
$3.50
End Date: Friday Jan-12-2018 15:09:34 PST
Buy It Now for only: $3.50
Buy It Now | Add to watch list
Uno R3 CH340G Board With 8-Bit LED Digital Tube 8 Keys TM1638 Display Arduino
$6.49
End Date: Friday Jan-12-2018 14:02:57 PST
Buy It Now for only: $6.49
Buy It Now | Add to watch list


Leave a Reply

Your email address will not be published. Required fields are marked *