1. 程式人生 > 資料庫 >如何使用nginx充當mysql的負載均衡器

如何使用nginx充當mysql的負載均衡器

說明:nginx版本要求是1.9以上 ,編譯nginx的時候需要加上 --with-stream

如:

./configure --prefix=/Data/apps/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-stream

注意

1.因為mysql預設使用了3306埠所以配置nginx tcp反向代理mysql的時候注意埠不要與mysql監聽的埠一樣比如我使用的是3307

2.確保能root使用者能遠端連線mysql

如資料庫mysql 表user

nginx.conf

此段程式碼追加在nginx.conf檔案末尾,注意不能加在http{}內

stream{
include /Data/apps/nginx/conf/stream/*.conf;
}

stream/db.conf

server {
listen 3307; #注意埠不能跟mysql監聽的一樣
proxy_pass db;
}
upstream db {
server 127.0.0.1:3306;
server 192.168.233.1:3306;
}

重啟nginx,檢視nginx是否監聽了3307埠

然後php程式碼是這樣子

#其實就是new mysqli的時候只需改埠號與nginx反向代理設定的埠號一樣就可以了
$mysqli = new mysqli('127.0.0.1','root','test',3307);

完整的php程式碼

<?php
class MysqlClass
{
private static $obj = NULL; //mysqlclass物件
public $host;
public $database;
public $user;
public $pwd;
public $port;
public $mysqli = NULL;
//禁止物件被克隆
private function __clone(){}
//禁止外部例項化
private function __construct($host="127.0.0.1",$database="test",$user="root",$pwd="root",$port="3307")
{
$this->host = $host;
$this->database = $database;
$this->user = $user;
$this->pwd = $pwd;
$this->port = $port;
$this->mysqli = $this->db_connect();
}
//獲取mysqli連線
private function db_connect()
{
$mysqli = new mysqli($this->host,$this->user,$this->pwd,$this->database,$this->port);
if($mysqli->connect_errno)
{
printf("Connect failed: %s\n",$mysqli->connect_errno);
exit();
}
$mysqli->query("set names utf8 ");
return $mysqli;
}
//獲取db例項
public static function get_db()
{
if(self::$obj === NULL)
{
self::$obj = new self();
}
return self::$obj;
}
public function db_query($sql)
{
$result = $this->mysqli->query($sql);
$arr = [];
while ($row = $result->fetch_assoc()) {
$arr[] = $row;
}
$result->close();
$this->mysqli->close();
return $arr;
}
public function db_insert()
{
}
public function db_update()
{
}
public function __destruct() {
$this->mysqli->close();
}
}
$db = MysqlClass::get_db();
$r = $db->db_query("show tables");
var_dump($r);

結果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。