douling6469 2011-11-22 20:36
浏览 364
已采纳

数据库复制:PHP中的智能数据库选择?

I'm using PHP with a replicated MySQL database.

I want to do some database load balancing. Currently I have the rather crude:

$ran = rand(1,10);
if ($ran < 5) {
  $db = '10.0.0.2:3306';
} else {
  $db = '10.0.0.3:3306';
}
// connect to the database
$con = mysql_connect($db,'elastic1','oag4Chai')
    or die('Could not connect to the server!');

But obviously if one of the databases is down, then our web pages will show error messages half the time.

Is there a more robust way to do this - i.e. check if the database is up before connecting?

It could be just a try/catch statement I guess, or I could do some more sophisticated load balancing - suggestions gratefully received.

  • 写回答

4条回答 默认 最新

  • donglu7816 2011-11-22 20:38
    关注

    Its not the web page, that shows the errors, its you

    die('Could not connect to the server!')
    

    die() has nothing to do in "real code" nowadays.

    $ran = rand(1,10);
    if ($ran < 5) {
      $db = '10.0.0.2:3306';
    } else {
      $db = '10.0.0.3:3306';
    }
    // connect to the database
    $con = mysql_connect($db,'elastic1','oag4Chai');
    if (!$con) { /* Connect to the other one */ }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码