咔叽游戏

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 792|回复: 0

[nginx] 如何使用nginx充当mysql的负载均衡器

[复制链接]

该用户从未签到

发表于 2020-4-30 18:33:39 | 显示全部楼层 |阅读模式
说明: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充当mysql的负载均衡器-1.jpg

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端口
如何使用nginx充当mysql的负载均衡器-2.jpg

然后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: %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);结果
如何使用nginx充当mysql的负载均衡器-3.jpg

如何使用nginx充当mysql的负载均衡器-4.jpg

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持咔叽网单www.2nzz.com。


原文地址:https://www.jb51.net/article/163994.htm

QQ|免责声明|小黑屋|手机版|Archiver|咔叽游戏

GMT+8, 2024-3-29 07:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表