简体   繁体   English

循环连接到mysql

[英]Round robin connects to mysql

I want to load balance queries to 2 mysql servers, in my application. 我想在我的应用程序中将余量查询加载到2个mysql服务器。

What would be the best way to do that, so that each query goes to a different db server? 最好的方法是什么,以便每个查询转到不同的数据库服务器?

I am thinking of having a global counter which is incremented each time a connection is made, mod the counter with my db servers in order to get the host I should connect. 我想有一个全局计数器,每次建立连接时都会递增,使用我的数据库服务器修改计数器,以获得我应该连接的主机。 The above process however needs to be atomic, so that no 2 requests see the same counter. 然而,上述过程需要是原子的,因此没有2个请求看到相同的计数器。

How should I go about it? 我该怎么办呢? Use a semaphore lock, mysql's get_lock()? 使用信号量锁,mysql的get_lock()?

pseudo code 伪代码

counter = 0
hosts = array('192.168.1.1:3306', '192.168.1.2:3306')

//the below code needs to be atomic
GET A GLOBAL LOCK
counter = counter+1
RELEASE THE LOCK

host = hosts[counter % len(hosts)]

Thanks 谢谢

The best way? 最好的方法?

Use MySQL Proxy ... It'll automatically compensate for down servers. 使用MySQL代理 ...它会自动补偿服务器的下行。 Plus you can write rules that state where each query goes (either round robin choice, or to a specific server for better cache affinity). 另外,您可以编写规则来说明每个查询的位置(循环选择,或者指定特定服务器以获得更好的缓存关联)。 Plus, it can automatically direct all writes to the master server... 另外,它可以自动将所有写入指向主服务器......

I wouldn't try implementing it in your application. 我不会尝试在您的应用程序中实现它。 The reason is that it's a lot harder to deal with global locks across multiple instances, and it's harder to have fault detection that doesn't result in a large performance hit... 原因是在多个实例中处理全局锁定要困难得多,并且更难以进行故障检测而不会导致大的性能损失......

why not just go with a rand approach? 为什么不采用rand方法呢?

$this->read_host = $this->prod_slaves_array[rand(0,(count($this->prod_slaves_array)-1))];

advantages are that it is lockless, and though it is not completely 50/50, does it really need to be? 优点是它是无锁的,虽然它不是完全50/50,它真的需要吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM