Home > Backend Development > PHP Tutorial > How to achieve load balancing in php? PHP load balancing example (code)

How to achieve load balancing in php? PHP load balancing example (code)

不言
Release: 2023-04-03 12:18:01
Original
13573 people have browsed it

There are many ways to implement load balancing in PHP. Here, I will introduce to you PHP load balancing. Without further ado, let’s take a look directly at the implementation of PHP load balancing.

1. PHP files

The first question is, if you have a large number of small servers, how do you upload your php files to all of them On the server? There are the following methods for your reference:

1. Upload all files to each server separately. The problem with this method is: imagine that you have 20 servers, then the upload process will be very long. It is easy to cause errors, and it is very likely that when updating, there will be different versions of files on different servers.
2. Use ‘rsync ‘ (or similar software). Such a tool can synchronize files on a local directory and multiple remote host directories.
3. Use version control software (such as subversion). This is my favorite method. It allows me to maintain my code very well, and when I publish my application, I can run the svnupdate command on each server to synchronize it. This approach also makes it easier to switch servers to a previous version of the code.
4. Use a file server (you may find that NFS is very suitable for this). This method is to use a file server to store your web application. Of course, if your file server goes down, so all Your site will be unavailable. At this time, you will need to spend more money to restore it.

Which method you choose depends on your needs and the skills you have. If you use a version control system, then you may want to plan a way to update the code on all servers by executing an update command at the same time. However, if you use a file server, you will need to implement some failure recovery mechanism to prevent request failures in the event that the server goes down.

2. File upload

When there is only one server, file upload is not a problem. But when we have multiple servers, how should the uploaded files be stored? The problem of uploading files is similar to cross-server PHP file storage. Here are several possible solutions:
1. Store the file in the database.

Most data allows binary data to be stored. When you request a file download, access data outputs the binary data and the corresponding file name and type to the user. You should consider how the database will store your files before using this solution. The problem with this approach is that if the database server goes down it will make the files unavailable.

2. Store uploaded files on a file server.

Same as the previous introduction, you need to install a file server to be shared by all web servers and upload all uploaded files here , all web servers can use it after uploading. However, if the file server is down, image file download interruptions may occur.

3. Design your own upload mechanism to transfer files to each server.

This method does not have the disadvantages of a single file server or database solution, but will increase the complexity of your code. For example, if the server goes down during uploading to multiple servers, what will you do?

Using a database to store uploaded files but designing a file caching mechanism is a good solution. When the server receives a file download request, it first checks whether the file exists in the cache system. If found, it downloads it from the cache system. Otherwise, it reads it from the database and caches it in the file system.

3. Sessions

If you are familiar with php session processing, you will probably know that by default, it Store session data in temporary files on the server. Moreover, this file is only on the server where you requested it, but subsequent requests may be processed by another server, which will generate a new session on the other server. This causes sessions to be frequently unrecognized, such as logged-in users always being asked to log in again.

My recommended solution is to either re-store session data into the database using PHP's built-in session processing mechanism, or implement your own mechanism to ensure that a user's request is sent to the same server.

4. Configuration

Although this topic is not particularly related to PHP, I feel it is still necessary to mention it. When running clustered servers, it is a good idea to have some way of keeping configuration files in sync between servers. If the configuration files are inconsistent, it can result in some very strange intermittent behavior that can be difficult to troubleshoot.

I recommend using a version control system to manage them individually. This way you can store different php configuration files for different project installations, and also keep all server configuration files in sync.

5. Logging

Like configuration issues, logging is not just related to PHP. But it's still very important to keep your server running healthy. Without a proper logging system, how would you know if your PHP code starts generating errors (you always turn off the display_errors setting when the system is officially running, don't you?)

There are several ways you can implement logging:

1. Record logs on each server. This is the simplest way. Each machine records only one file. The advantage is that it is simple and may require very little configuration. However, as the number of servers increases, monitoring the log files on each server becomes very difficult.
2. Record logs to a share This method each server still has the log files, but they are stored on a central file server through the sharing mechanism, which will make monitoring the logs easier. The problem with this solution is that if the file server is unavailable, a simple log write problem will eventually cause the entire application to crash.
3. Record logs to a logging server. You can use a logging software, such as syslog, to write all logs to a central server. Although this method requires more configuration, it also provides the most robust solution.

php load balancing instance

If you want to use load balancing, you can modify the configuration of the http node as follows:

#设定http服务器,利用它的反向代理功能提供负载均衡支持
            http {
            #设定mime类型,类型由mime.type文件定义
            include       /etc/nginx/mime.types;
            default_type  application/octet-stream;
            #设定日志格式
            access_log    /var/log/nginx/access.log;
#省略上文有的一些配置节点
#。。。。。。。。。。
#设定负载均衡的服务器列表
            upstream mysvr {
            #weigth参数表示权值,权值越高被分配到的几率越大
            server 192.168.8.1x:3128 weight=5;#本机上的Squid开启3128端口
            server 192.168.8.2x:80  weight=1;
            server 192.168.8.3x:80  weight=6;
            }
upstream mysvr2 {
            #weigth参数表示权值,权值越高被分配到的几率越大
server 192.168.8.x:80  weight=1;
            server 192.168.8.x:80  weight=6;
            }
#第一个虚拟服务器
            server {
            #侦听192.168.8.x的80端口
            listen       80;
            server_name  192.168.8.x;
#对aspx后缀的进行负载均衡请求
            location ~ .*\.aspx$ {
root   /root;      #定义服务器的默认网站根目录位置
            index index.php index.html index.htm;   #定义首页索引文件的名称
proxy_pass  http://mysvr ;#请求转向mysvr 定义的服务器列表
#以下是一些反向代理的配置可删除.
proxy_redirect off;
#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            client_max_body_size 10m;    #允许客户端请求的最大单文件字节数
            client_body_buffer_size 128k;  #缓冲区代理缓冲用户端请求的最大字节数,
            proxy_connect_timeout 90;  #nginx跟后端服务器连接超时时间(代理连接超时)
            proxy_send_timeout 90;        #后端服务器数据回传时间(代理发送超时)
            proxy_read_timeout 90;         #连接成功后,后端服务器响应时间(代理接收超时)
            proxy_buffer_size 4k;             #设置代理服务器(nginx)保存用户头信息的缓冲区大小
            proxy_buffers 4 32k;               #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
            proxy_busy_buffers_size 64k;    #高负荷下缓冲大小(proxy_buffers*2)
            proxy_temp_file_write_size 64k;  #设定缓存文件夹大小,大于这个值,将从upstream服务器传
}
}
Copy after login

Related Recommended:

Detailed explanation of session sharing cases under PHP load balancing (with code)

The above is the detailed content of How to achieve load balancing in php? PHP load balancing example (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template