I am thinking of making a poor man’s application level load balancer for static content (i.e., images). I was wondering if this is the best way to do it. Let me explain in code:
Sample HTML page:
<html>
<body>
<?=load_image('filename.jpg');
</body>
</html>
Sample code in PHP:
<?php
function load_image ($file)
{
$server = get_current_server();
update_next_server($server);
return '<img src="'.$server.$file.'" />';
}
function update_next_server ($server)
{
$a[1] = 'server1.com';
$a[2] = 'server2.com';
$a[3] = 'server3.com';
$server_id = array_search($server, $a); // example: if $server = 'server2.com' then this will return 2;
// increment next server id
$server_id = $server_id + 1;
// prevent going beyond valid server ids
if ($server_id >= 3)
$server_id = 1;
$db->query('UPDATE tbl_next_server SET server_id = "'.$server_id.'" ');
}
function get_current_server ()
{
return $db->query('SELECT server_id FROM tbl_next_server');
}
Basically this assumes the same images are stored in all three server and it just rotates the server every time the page is viewed.
Now my question is, is this the best way to do this or are there better ways?
In your code – 2 queries for image one. Isn’t it too much?
You must watch what loads more – database\filesystem\memory\processor load? Depending on this solution can be provided by in many ways. For example if DB is overloaded, u can try to store
last_server_usedvalue on disk (e.g. in session storage).P.S. Anyway i dont see any reason to output images\static(e.g.) with any php code. It’s
nginxjob to output static content. So i highly recommend you to try write same balancer on other server configuration files.