微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

nginx的负载均衡和反向代理

1、Nginx负载均衡中常见的算法及原理有哪些?

#1)轮询 (round-robin)
轮询为负载均衡中较为基础也较为简单的算法,它不需要配置额外参数。假设配置文件中共有 台服务器,该算法遍历服务器节点列表,并按节点次序每轮选择一台服务器处理请求。当所有节点均被调用过一次后,该算法将从第一个节点开始重新一轮遍历。
特点:由于该算法中每个请求按时间顺序逐一分配到不同的服务器处理,因此适用于服务器性能相近的集群情况,其中每个服务器承载相同的负载。但对于服务器性能不同的集群而言,该算法容易引发资源分配不合理等问题。
配置样例:
upstream backserver {
server 192.168.0.10;
server 192.168.0.20;
}

#2)加权轮询(weight round robin)
为了避免普通轮询带来的弊端,加权轮询应运而生。在加权轮询中,每个服务器会有各自的 weight。一般情况下,weight 的值越大意味着该服务器的性能越好,可以承载更多的请求。该算法中,客户端的请求按权值比例分配,当一个请求到达时,优先为其分配权值最大的服务器。
特点:加权轮询可以应用于服务器性能不等的集群中,使资源分配更加合理化。
配置样例:
upstream backserver {
server 192.168.0.10 weight=10;
server 192.168.0.20 weight=20;
}

#3)源地址hash(ip_hash)
ip_hash 依据发出请求的客户端 IP 的 hash 值来分配服务器,该算法可以保证同 IP 发出的请求映射到同一服务器,或者具有相同 hash 值的不同 IP 映射到同一服务器。
特点:该算法在一定程度上解决了集群部署环境下 Session 不共享的问题。实际应用中,我们可以利用 ip_hash,将一部分 IP 下的请求转发到运行新版本服务的服务器,另一部分转发到旧版本服务器上,实现灰度发布。再者,如遇到文件过大导致请求超时的情况,也可以利用 ip_hash 进行文件的分片上传,它可以保证同客户端发出的文件切片转发到同一服务器,利于其接收切片以及后续的文件合并操作。
配置样例:
upstream backserver {
ip_hash;
server 192.168.0.10;
server 192.168.0.20;
}

#4)目的Url hash(url_hash)
url_hash 是根据请求的 URL 的 hash 值来分配服务器。该算法的特点是,相同 URL 的请求会分配给固定的服务器,当存在缓存的时候,效率一般较高。
配置样例:
upstream backserver {
hash $request_uri;
hash_method crc32;
server 192.168.0.10;
server 192.168.0.20;
}

#5)最少连接数(least_conn)
假设共有n台服务器,当有新的请求出现时,遍历服务器节点列表并选取其中连接数最小的一台服务器来响应当前请求。连接数可以理解为当前处理的请求数。
配置样例:
upstream backserver {
least_conn;
server 192.168.0.10;
server 192.168.0.20;
}

#6)最快响应时间(fair)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。
配置样例:
upstream backserver {
fair;
server 192.168.0.10;
server 192.168.0.20;
}

#upstream还能为每一个设备设置状态值,这些值的含义如下:
down 表示单前的server暂时不参与负载.
weight 认为1.weight越大,负载的权重就越大。
max_fails :允许请求失败的次数认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误.
fail_timeout : max_fails次失败后,暂停的时间。
backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

2、使用rewrite规则实现将所有到a域名的访问rewrite到b域名

[root@centos8 ~]#vim /apps/Nginx/conf/conf.d/mobile.conf
server {
 listen 80;
 server_name www.a.com;
 location / {
        root "/data/Nginx/html/mobile";
        index index.html;
        rewrite / http://www.b.com redirect;
}
}

server {
 listen 80;
 server_name www.b.com;
 location / {
        root "/Nginx/html/";
        index index.html;
 }
}

[root@centos8 ~]#echo 111 > /data/Nginx/html/mobile/index.html
[root@centos8 ~]#echo 222 > /Nginx/html/index.html
[root@centos8 ~]#vim /etc/hosts
10.0.0.150  www.a.com www.b.com

[root@centos8 ~]#curl www.a.com
<html>
<head><title>302 Found</title></head>
<body>
<center><h1>302 Found</h1></center>
<hr><center>Nginx/1.18.0</center>
</body>
</html>

[root@centos8 ~]#curl -L www.a.com
222

3、实现反向代理客户端IP透传

#1)一级代理实现客户端IP透传
#目标:实现客户端通过一个反向代理Nginx服务器访问到web服务器,在web、Nginx服务器日志记录有客户端ip地址。
环境准备:
client:10.0.0.160/24
proxy(Nginx):10.0.0.150/24
web(apache):10.0.0.152/24

#Nginx配置
[root@Nginx ~]#vim /apps/Nginx/conf/conf.d/pc.conf
server {
  listen 80;
  server_name www.abc.com;
  location / {
    index index.html index.PHP;
    root /data/Nginx/html/pc;
    proxy_pass http://10.0.0.152;
    #proxy_set_header X-Real-IP $remote_addr;                   #只添加客户端IP到
请求报文头部,转发至后端服务器
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #添加客户端IP和反
向代理服务器IP到请求报文头部
  }
}
[root@Nginx ~]#systemctl restart Nginx

#apache配置
[root@web ~]# vim /etc/httpd/conf/httpd.conf
LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
[root@web ~]# echo web > /var/www/html/index.html
[root@web ~]#systemctl restart httpd
#客户端配置
[root@client ~]#echo 10.0.0.152 www.abc.com >> /etc/hosts
[root@client ~]#curl www.abc.com
web

#Nginx配置
[root@Nginx ~]#cat /apps/Nginx/conf/Nginx.conf|grep x_forwarded
    #                  '"$http_user_agent" "$http_x_forwarded_for"';#认有此配置

[root@Nginx ~]#echo 10.0.0.152 www.abc.com >> /etc/hosts
[root@Nginx ~]#curl www.abc.com
web

#在apache服务器查看日志,验证。
[root@web ~]# cat /var/log/httpd/access_log
10.0.0.160 10.0.0.150 - - [29/Nov/2021:10:35:20 +0800] "GET / HTTP/1.0" 200 4 "-" "curl/7.61.1"
- 10.0.0.150 - - [29/Nov/2021:10:38:35 +0800] "GET / HTTP/1.1" 200 4 "-" "curl/7.61.1"


#2)多级代理实现客户端 IP 透传
client:10.0.0.160
Nginx1:10.0.0.150
Nginx2:10.0.0.170
apache:10.0.0.152
#第一个代理服务器
[root@Nginx1 ~]#echo 10.0.0.170 www.abcd.com >> /etc/hosts
[root@Nginx1 ~]#vim /apps/Nginx/conf/Nginx.conf 
#开启日志格式,记录x_forwarded_for
http {
   include       mime.types;
   default_type application/octet-stream;
   proxy_cache_path /data/Nginx/proxycache   levels=1:1:1 
keys_zone=proxycache:20m inactive=120s  max_size=1g;
   log_format main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
   access_log logs/access.log main;
#定义反向代理
[root@Nginx ~]#cat /apps/Nginx/conf/conf.d/pc.conf
server {
  listen 80;
  server_name www.abc.com;
  location / {
    proxy_pass http://www.abcd.com;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

}

#第二个代理服务器
[root@Nginx2 ~]#vim /apps/Nginx/conf/Nginx.conf 
#开启日志格式,记录x_forwarded_for
http {
   include       mime.types;
   default_type application/octet-stream;
   proxy_cache_path /data/Nginx/proxycache   levels=1:1:1 
keys_zone=proxycache:20m inactive=120s  max_size=1g;
   log_format main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
   access_log logs/access.log main;
#定义反向代理
[root@Nginx2 ~]# cat /etc/Nginx/conf.d/pc.conf
server {
  listen 80;
  server_name www.abcd.com;
  location / {
    proxy_pass http://10.0.0.152;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    root /data/html/index.html;
  }
}

#在client访问测试
[root@client ~]#curl www.abc.com
web
hello


#在第一个proxy上面查看日志
[root@Nginx1 ~]#tail /apps/Nginx/logs/access.log -f
10.0.0.160 - - [29/Nov/2021:13:32:54 +0800] "GET / HTTP/1.1" 200 10 "-" "curl/7.61.1" "-"

#在第二个proxy上面查看日志
[root@Nginx2 ~]#tail -f /var/log/Nginx/access.log
10.0.0.150 - - [29/Nov/2021:13:32:54 +0800] "GET / HTTP/1.0" 200 10 "-" "curl/7.61.1" "10.0.0.160"

#在apache上面查看日志
[root@web ~]# tail -f /etc/httpd/logs/access_log
"10.0.0.160, 10.0.0.150" 10.0.0.170 - - [29/Nov/2021:13:32:54 +0800] "GET / HTTP/1.0" 200 10 "-" "curl/7.61.1"

4、利用LNMP实现wordpress站点搭建"

#环境准备:
Nginx+PHP+wordpress   10.0.0.152
MysqL+redis           10.0.0.162

#在10.0.0.162编写脚本实现mysqk数据库一键安装
[root@localhost ~]# cat install_MysqL.sh
#!/bin/bash
#
#**********************************************************************************************
. /etc/init.d/functions
SRC_DIR=`pwd`
MysqL='mysql-8.0.19-linux-glibc2.12-x86_64.tar.xz'
COLOR='echo -e \E[01;31m'
END='\E[0m'
MysqL_ROOT_PASSWORD=123456


check (){
if [ $UID -ne 0 ]; then
 action "当前用户不是root,安装失败" false
 exit 1
fi

cd $SRC_DIR
if [ ! -e $MysqL ];then
        $COLOR"缺少${MysqL}文件"$END
        $COLOR"请将相关软件放在${SRC_DIR}目录下"$END
        exit
elif [ -e /usr/local/MysqL ];then
        action "数据库已存在,安装失败" false
        exit
else
 return
fi
}


install_MysqL(){
$COLOR"开始安装MysqL数据库..."$END
yum -y -q install libaio numactl-libs libaio &> /dev/null
cd $SRC_DIR
tar xf $MysqL -C /usr/local/
MysqL_DIR=`echo $MysqL| sed -nr 's/^(.*[0-9]).*/\1/p'`
ln -s /usr/local/$MysqL_DIR /usr/local/MysqL
chown -R root.root /usr/local/MysqL/
id MysqL &> /dev/null || { useradd -s /sbin/nologin -r MysqL ; action "创建MysqL用户"; }

echo 'PATH=/usr/local/MysqL/bin/:$PATH' > /etc/profile.d/MysqL.sh
. /etc/profile.d/MysqL.sh
ln -s /usr/local/MysqL/bin/* /usr/bin/
[ -d /data/MysqL ] || mkdir -p /data/MysqL
cat > /etc/my.cnf <<EOF
[MysqLd]
server-id=`hostname -I|cut -d. -f4`
log-bin
datadir=/data/MysqL
socket=/data/MysqL/MysqL.sock
log-error=/data/MysqL/MysqL.log
pid-file=/data/MysqL/MysqL.pid
[client]
socket=/data/MysqL/MysqL.sock
EOF


MysqLd --initialize --user=MysqL --datadir=/data/MysqL
cp /usr/local/MysqL/support-files/MysqL.server /etc/init.d/MysqLd
chkconfig --add MysqLd
chkconfig MysqLd on
service MysqLd start
[ $? -ne 0 ] && { $COLOR"数据库启动失败,退出!"$END;exit; }
MysqL_OLDPASSWORD=`awk '/A temporary password/{print $NF}' /data/MysqL/MysqL.log`
MysqLadmin -uroot -p$MysqL_OLDPASSWORD password $MysqL_ROOT_PASSWORD&>/dev/null
action "数据库安装完成"
}

check
install_MysqL

#执行脚本进行数据库安装
[root@localhost ~]# bash install_MysqL.sh
开始安装MysqL数据库...
创建MysqL用户                                              [  OK  ]
Starting MysqL.                                           [  OK  ]
数据库安装完成											[  OK  ]

#创建数据库用户并授权
[root@localhost ~]# MysqL -uroot -p123456

MysqL> create database wordpress;
Query OK, 1 row affected (0.01 sec)

MysqL> create user wordpress@'10.0.0.%' identified by '123456';
Query OK, 0 rows affected (0.00 sec)

MysqL> grant all on wordpress.* to wordpress@'10.0.0.%';
Query OK, 0 rows affected (0.00 sec)

#在10.0.0.152wordpress上连接数据库测试
#安装MysqL客户端
[root@localhost ~]#yum install -y MysqL
[root@localhost ~]# MysqL -uwordpress -h10.0.0.162 -p123456
ERROR 2059 (HY000): Authentication plugin 'caching_sha2_password' cannot be loaded: /usr/lib64/MysqL/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory

连接MysqL数据库时会出现Authentication plugin 'caching_sha2_password' cannot be loaded的错误。
出现这个原因是MysqL8 之前的版本中加密规则是MysqL_native_password,而在MysqL8之后,加密规则是caching_sha2_password, 解决问题方法是把MysqL用户登录密码加密规则还原成MysqL_native_password. 

#返回10.0.0.162,修改密码规则
MysqL> ALTER USER wordpress@'10.0.0.%'  IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
Query OK, 0 rows affected (0.00 sec)

MysqL> ALTER USER wordpress@'10.0.0.%'  IDENTIFIED WITH MysqL_native_password BY '123456';
Query OK, 0 rows affected (0.00 sec)

MysqL>  FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.01 sec)

#返回10.0.0.152连接数据库
[root@localhost ~]# MysqL -uwordpress -h10.0.0.162 -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MysqL connection id is 31
Server version: 8.0.19 MysqL Community Server - GPL

copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MysqL [(none)]>


#10.0.0.152上编写脚本安装PHP-fpm
[root@localhost]#vim install_PHP.sh
yum -y install gcc openssl-devel libxml2-devel bzip2-devel libmcrypt-devel sqlite-devel oniguruma-devel &>/dev/null
cd /usr/local/src
wget https://www.PHP.net/distributions/PHP-7.4.11.tar.xz &>/dev/null
tar -xf PHP-7.4.11.tar.xz
cd PHP-7.4.11
./configure --prefix=/apps/PHP74 --enable-MysqLnd --with-MysqLi=MysqLnd --with-pdo-MysqL=MysqLnd --with-openssl --with-zlib --with-config-file-path=/etc --with-config-file-scan-dir=/etc/PHP.d --enable-mbstring --enable-xml --enable-sockets --enable-fpm --enable-maintainer-zts --disable-fileinfo  &>/dev/null
make&&make install &>/dev/null
cp /usr/local/src/PHP-7.4.11/PHP.ini-production /etc/PHP.ini
cp /apps/PHP74/etc/PHP-fpm.conf.default  /apps/PHP74/etc/PHP-fpm.conf
cp /apps/PHP74/etc/PHP-fpm.d/www.conf.default /apps/PHP74/etc/PHP-fpm.d/www.conf
cat >/apps/PHP74/etc/PHP-fpm.d/www.conf <<eof
[www]
user = www
group = www
listen = 127.0.0.1:9000
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
pm.status_path = /pm_status
ping.path = /ping
access.log = log/$pool.access.log
slowlog = log/$pool.log.slow
eof
useradd -r -s /sbin/nologin www
mkdir /apps/PHP74/log
/apps/PHP74/sbin/PHP-fpm -t &>/dev/null
[ $? -ne 0 ] && { echo "PHP-fpm启动失败,退出!";exit; }
cp /usr/local/src/PHP-7.4.11/sapi/fpm/PHP-fpm.service /usr/lib/systemd/system/
systemctl daemon-reload
systemctl enable --Now PHP-fpm  &>/dev/null
[ $? -eq 0 ] && { echo "PHP-fpm is enabled"; }
pstree -p |grep PHP &>/dev/null
[ $? -eq 0 ] && { echo "PHP-fpm sever is running"; }

[root@localhost ~]# bash install_PHP.sh
PHP-fpm is enabled
PHP-fpm sever is running



#编写Nginx安装脚本进行安装
[root@localhost ~]# cat install_Nginx.sh
#!/bin/bash
yum -y install gcc pcre-devel openssl-devel zlib-devel &>/dev/null
[ $? -eq 0 ] && { echo "gcc pcre-devel openssl-devel zlib-devel is install"; }

cd /usr/local/src/
wget http://Nginx.org/download/Nginx-1.18.0.tar.gz &>/dev/null
tar xf Nginx-1.18.0.tar.gz
cd Nginx-1.18.0/
./configure --prefix=/apps/Nginx --user=www --group=www --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module &>/dev/null
[ $? -eq 0 ] && { echo "编译完成"; }
make &>/dev/null
make install &>/dev/null
[ $? -eq 0 ] && { echo "Nginx编译安装完成"; }
cat >/usr/lib/systemd/system/Nginx.service <<eof
[Unit]
Description=Nginx - high performance web server
Documentation=http://Nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/apps/Nginx/run/Nginx.pid
ExecStart=/apps/Nginx/sbin/Nginx -c /apps/Nginx/conf/Nginx.conf
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=/bin/kill -s TERM \$MAINPID
[Install]
WantedBy=multi-user.target
eof

mkdir /apps/Nginx/run/ -p
mv /apps/Nginx/conf/Nginx.conf{,.bak}
cat >/apps/Nginx/conf/Nginx.conf <<eof
worker_processes 1;
pid /apps/Nginx/run/Nginx.pid;
events {
    worker_connections 1024; }
http {
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;
    server {
        listen 80;
        server_name www.magedu.org;
        location / {
            root /data/Nginx/wordpress;
            index index.PHP index.html index.htm;
        }
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root html;
        }
        location ~ \.PHP$ {
            root /data/Nginx/wordpress;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.PHP;
            fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
            include fastcgi_params;
        }
        location ~ ^/(ping|pm_status)$ {
            include fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param PATH_TRANSLATED \$document_root\$fastcgi_script_name;
        }
    }
}
eof
ln -s  /apps/Nginx/sbin/Nginx /usr/sbin/Nginx
/apps/Nginx/sbin/Nginx -t &>/dev/null
[ $? -eq 0 ] && { echo "configuration file /apps/Nginx/conf/Nginx.conf test is successful!"; }
systemctl daemon-reload
systemctl enable --Now Nginx &>/dev/null
[ $? -eq 0 ] && { echo "Nginx启动成功!"; }
mkdir -p /data/Nginx/wordpress
cat> /data/Nginx/wordpress/test.PHP <<eof
<?PHP
PHPinfo();
?>
eof

[root@localhost ~]# bash install_Nginx.sh
Nginx编译安装完成
configuration file /apps/Nginx/conf/Nginx.conf test is successful!
Nginx启动成功!

#测试访问PHP测试页正常
[root@localhost ~]#curl localhost/test.PHP


#在10.0.0.152上部署wordpress
[root@www ~]# tar xf wordpress-5.4.1-zh_CN.tar.gz
[root@www ~]# cp -r wordpress/* /data/Nginx/wordpress
[root@www ~]# chown -R www.www /data/Nginx/wordpress/
#在windows访问http://www.magedu.org
[root@www ~]# vim /data/Nginx/wordpress/wp-config.php
#在wordpress文章并发布
#验证发表的文章网页访问http://www.magedu.org
[root@www ~]# tree /data/Nginx/wordpress/wp-content/uploads/
/data/Nginx/wordpress/wp-content/uploads/
└── 2021
    └── 11
        └── timg.jpg

2 directories, 1 file
You have mail in /var/spool/mail/root
#配置允许上传文件
#注意:认只支持1M以下文件上传,要利用PHP程序上传图片,还需要修改下面三项配置,最大上传由三项值的最小值决定
#Nginx上传文件大小限制
[root@centos7 ~]#vim /apps/Nginx/conf/Nginx.conf
server {
       client_max_body_size 10m; #认值为1M
.....
#PHP上传文件大小限制
[root@centos7 ~]#vim /etc/PHP.ini
post_max_size = 30M   #认值为8M
upload_max_filesize = 20M  #认值为2M
[root@centos7 ~]#systemctl restart Nginx PHP-fpm


#安全加固
[root@www ~]# vim /apps/Nginx/conf/Nginx.conf
worker_processes 1;
pid /apps/Nginx/run/Nginx.pid;
events {
    worker_connections 1024; }
http {
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;
    server {
        listen 80;
        server_name www.magedu.org;
        client_max_body_size 10m;
        server_tokens off;#添加此行,隐藏Nginx版本
        location / {
            root /data/Nginx/wordpress;
            index index.PHP index.html index.htm;
        }
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root html;
        }
        location ~ \.PHP$ {
            root /data/Nginx/wordpress;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.PHP;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            fastcgi_hide_header X-Powered-By;#添加此行
        }
        location ~ ^/(ping|pm_status)$ {
            include fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param PATH_TRANSLATED $document_root$fastcgi_script_name;
        }
    }
}
[root@www ~]# systemctl reload Nginx

#开启opcache加速
[root@www ~]# vim /etc/PHP.ini
[opcache]
; Determines if Zend OPCache is enabled
zend_extension=opcache.so
opcache.enable=1
[root@www ~]# #systemctl restart PHP-fpm

#PHP 扩展session模块支持redis
PECL是 PHP 扩展的存储库,提供用于下载和开发 PHP 扩展的所有已知扩展和托管功能的目录
官方链接: http://pecl.PHP.net/package-stats.PHP
github: https://github.com/PHPredis/PHPredis
github安装文档: https://github.com/PHPredis/PHPredis/blob/develop/INSTALL.markdown
开始在 PHP 中使用 Redis 前, 需要确保已经安装了 redis 服务及 PHP redis 驱动,
PHP redis 驱动下载地址为:https://github.com/PHPredis/PHPredis/releases

#在10.0.0.152上安装PHP redis 驱动
[root@www ~]# cd /usr/local/src/
[root@www ~]#tar xf PHPredis-5.3.3.tar.gz
[root@www src]# cd PHPredis-5.3.3/
[root@www PHPredis-5.3.3]#/apps/PHP74/bin/PHPize
[root@www PHPredis-5.3.3]# ./configure --with-PHP-config=/apps/PHP74/bin/PHP-config
[root@www PHPredis-5.3.3]#make -j 2 && make install
[root@www PHPredis-5.3.3]#
[root@www PHPredis-5.3.3]# ll /apps/PHP74/lib/PHP/extensions/no-debug-zts-20190902/
total 9588
-rwxr-xr-x 1 root root 4647668 Nov 29 15:53 opcache.a
-rwxr-xr-x 1 root root 2509416 Nov 29 15:53 opcache.so
-rwxr-xr-x 1 root root 2658240 Nov 30 02:31 redis.so

#编辑PHP配置文件支持redis

[root@www PHPredis-5.3.3]# vim /etc/PHP.ini
extension=redis.so    #文件最后一行添加此行,路径可省略
[root@www PHPredis-5.3.3]#
[root@www PHPredis-5.3.3]# systemctl restart PHP-fpm
#windows网页访问http://www.magedu.org/test.PHP验证redis模块价值成功

#在10.0.0.162上安装和配置 redis 服务
[root@localhost ~]# yum install -y redis
[root@localhost ~]# vim /etc/redis.conf
bind 0.0.0.0
requirepass 123456
[root@localhost ~]#systemctl enable --Now redis
[root@localhost ~]#ss -tnlp

#在10.0.0.152主机配置PHP的session保存在redis服务
[root@localhost ~]#vim /etc/PHP.ini
[Session]
; Handler used to store/retrieve data.
; http://PHP.net/session.save-handler
session.save_handler = redis
session.save_path = "tcp://10.0.0.162:6379?auth=123456"  
[root@localhost ~]#systemctl restart PHP-fpm
#验证
[root@www PHPredis-5.3.3]# curl localhost/test.PHP|grep -i 'session.save_handler'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0<tr><td class="e">session.save_handler</td><td class="v">redis</td><td class="v">redis</td></tr>
100 71733    0 71733    0     0  9305k      0 --:--:-- --:--:-- --:--:--  9.7M


#10.0.0.152准备 PHP实现 session 的测试页面
[root@www PHPredis-5.3.3]# cat /data/Nginx/wordpress/session.PHP
<?PHP
session_start();
//redis用session_id作为key 并且是以string的形式存储
$redisKey = 'PHPREdis_SESSION:' . session_id();
// SESSION 赋值测试
$_SESSION['message'] = "Hello, I'm in redis";
$_SESSION['arr'] = [1, 2, 3, 4, 5, 6];
echo $_SESSION["message"] , "<br/>";
echo "Redis key =   " . $redisKey . "<br/>";
echo "以下是从Redis获取的数据", "<br/>";
// 取数据'
$redis = new Redis();
$redis->connect('10.0.0.162', 6379);
$redis->auth('123456');
echo $redis->get($redisKey);
?>

#网页访问http://www.magedu.org/session.PHP
[root@localhost ~]# redis-cli -h 10.0.0.162 -a 123456
10.0.0.162:6379> keys *
(empty list or set)
10.0.0.162:6379> keys *
1) "PHPREdis_SESSION:mgmr764old1jghlgqf6q5om8hj"
10.0.0.162:6379> get PHPREdis_SESSION:mgmr764old1jghlgqf6q5om8hj
"message|s:19:\"Hello, I'm in redis\";arr|a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}"
10.0.0.162:6379>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐