0

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 aa 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?

Slightz
  • 67
  • 9

2 Answers2

1

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);
  • i am getting a syntax error on my editor with this line: $servers = ['1.1.1.1','2.2.2.2','3.3.3.3']; – Slightz Dec 31 '16 at 15:38
  • nvm fixed it. used array('1.1.1.1','2.2.2.2','3.3.3.3'); also, i had to change the class name to new Memcache; was not working. Either way, thanks for this solution, does what I was looking. Gives the IP in order, thank you. – Slightz Dec 31 '16 at 15:51
  • @Slightz - Memcache and Memcached are two different extensions. Both basically do the same thing - you can read more about the differences here: http://stackoverflow.com/questions/1442411/when-should-i-use-memcache-instead-of-memcached – But those new buttons though.. Dec 31 '16 at 16:31
  • also, the `$servers` array in my code uses newer php syntax (http://docs.php.net/manual/en/language.types.array.php) which was introduced in php 5.4 – But those new buttons though.. Dec 31 '16 at 16:34
  • Oh did not know, I am using PHP 5.3.3 with PHP-fpm and Nginx on Ubuntu, regardless I got it working, which is what matters. thanks for the code! – Slightz Jan 01 '17 at 04:21
0

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 ) ];
DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70