Slightz
Slightz

Reputation: 67

Use randomizing for server load balancing?

I am using an array as an attempt for "load balance" several RTMP servers.

$servers = array(
    '1.1.1.1',
    '2.2.2.2',
);
$edge = $servers[array_rand($settings)];

but this code does not help much; I end up with 3k on one servers 2k in the other.

I was thinking of taking advantage of APC and cache the last IP given, to keep track of a better IP distribution among the users.

What I need is like the person gets IP 1.1.1.1 the next gets IP 2.2.2.2 to maintain the servers with a closer range of users instead of 3k on one and 2k in the other.

I could use MySQL, but I'll probably hammer the server with all the request.

What is the best way I can achieve a proper distribution of the IPs?

Upvotes: 0

Views: 391

Answers (2)

DiverseAndRemote.com
DiverseAndRemote.com

Reputation: 19888

Before you give up on a randomizing approach you should give the mt_rand function a try. It produces more random results than rand and array_rand.

$servers = array(
    '1.1.1.1',
    '2.2.2.2',
);
$num_servers = count( $servers );
$edge = $servers[ mt_rand( 0, $num_servers - 1 ) ];

Upvotes: 0

Eaten by a Grue
Eaten by a Grue

Reputation: 22931

Here's a simple example of how you could cycle three array keys using php memcached:

$servers = ['1.1.1.1','2.2.2.2','3.3.3.3'];
$m = new Memcached();
$m->addServer('localhost', 11211);
$key = $m->get('server');
if ($key === false) $key = 0;
echo $servers[$key];
if (++$key > count($servers) - 1) $key = 0;
$m->set('server', $key);

Upvotes: 1

Related Questions