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
Micro USB UNO R3 MEGA328P with CH340 CH340G Board for Arduino
$6.49
End Date: Thursday Mar-22-2018 17:55:30 PDT
Buy It Now for only: $6.49
Buy It Now | Add to watch list
NEW Arduino compatible UNO R3 ATMEGA328P CH340G Board + USB Cable + wires
$5.50
End Date: Wednesday Mar-21-2018 19:29:05 PDT
Buy It Now for only: $5.50
Buy It Now | Add to watch list
UNO R3 Ultimate Starter Kit For Arduino LCD Stepper Motor Servo 1602 COMPLETE
$38.97
End Date: Wednesday Mar-21-2018 13:39:28 PDT
Buy It Now for only: $38.97
Buy It Now | Add to watch list


Leave a Reply

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