nginx를 mysql의 로드 밸런서로 사용하는 방법

WBOY
풀어 주다: 2023-05-18 22:37:10
앞으로
1205명이 탐색했습니다.

참고: nginx 버전 요구 사항은 1.9 이상입니다. nginx를 컴파일할 때

./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
로그인 후 복사


Note

1과 같이 --with-stream

을 추가해야 합니다. 왜냐하면 mysql은 기본적으로 포트 3306을 사용하기 때문입니다. , nginx tcp 구성 mysql을 역방향으로 프록시할 때 포트는 mysql이 수신하는 포트와 동일하지 않습니다. 예를 들어 루트 사용자가 mysql

에 원격으로 연결할 수 있는지 확인하세요. 예: 데이터베이스 mysql 테이블 user

nginx.conf

nginx를 mysql의 로드 밸런서로 사용하는 방법

이 코드는 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);
로그인 후 복사

nginx를 mysql의 로드 밸런서로 사용하는 방법완전한 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의 로드 밸런서로 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:yisu.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!