說明: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','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:?%sn",?$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);
結果
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END