Frage

I'm writing a BI tool at work using PHP, which consists of one Linux + Apache + PHP machine serving reports and dashboards, containing data taken from our MySQL database. The database structure consists of a master (which I do not have access to) and two slaves, both of which I can run queries against. The idea here is that if one slave fails, the platform can continue to function reading data from the other. I plan to use a try/catch to failover from one machine to the other.

My question is, if both slaves are up then is there any way using PHP I can check which is least busy and then direct the query to this machine to balance the load between both servers optimally?

I've had a look around for answers here and I was surprised by how little there was, maybe I'm missing something obvious. A nudge in the right direction would be great.

Thanks in advance for any help,

James

War es hilfreich?

Lösung

I wouldn't use your PHP code to select a slave. It will either cost too much checking before all queries where to direct your requests, or not be smart enough to be a real load balancer.

First, it might be a good thing to just randomize your selection of a slave. This can be a good way to get the best division of labour between the slaves, but there are some catches.

If there are some extreme queries that cripple a slave you wouldn't want to do more queries there for abit, and if there is one client that favours slave1 above slave2, you might need to adjust for that, so it's not for all environments: in that case a dedicated (IP-level) load balancer that would redirect your (all?) traffic to the best machine seems like the best option.


You can find out the current load of a machine, as you said, with PHP.

if(file_exists("/proc/loadavg")) {
    $load = file_get_contents("/proc/loadavg");
    $load = explode(' ', $load);
}

But that's only for the local machine. To get this for a remote machine you could expose these values through a webserver: you can echo the contents of that file, or a bit better, make a small "webservice" that returns JSON or XML or whatever you like with these values.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top