search

版权声明:此文章转载自迹忆

原文地址: http://www.onmpw.com/tm/xwzj/network_144.html

如需转载请联系听云College团队成员阮小乙,邮箱:ruanqy#tingyun.com

集群的概念没有多复杂,其实就是多台电脑为了同一个目标在一起工作。在Web应用中,就是多个服务器提供一个站点的服务。

搭建PHP集群的第一步就是设置负载均衡。首先我们需要三台主机:

Nginx负载:192.166.5.111PHP应用1:192.168.5.112PHP应用2:192.168.5.113

先前,在PHP应用所在的主机,我们需要安装Nginx或者apache等这类web服务器,然后再在前面使用Nginx作为负载。Nginx 负载和php应用之间的通信是在应用层的,Nginx         负载其实就相当于一个代理。但是,现在情况不同了。Fastcgi技术的应用允许在php应用层可以不用再安装web服务器。现在PHP5.5版本已经将fpm作为内部模块支持了。在这种情况下,Nginx 负载和php应用之间的通信是在传输层的,二者之间使用socket进行通信。当然了,这需要fpm服务的支持。

Nginx设置

首先对Nginx(192.168.5.111)进行设置,编辑nginx.conf配置文件

http{         ……         upstream onmpw_phpApps{            server 192.168.18.88:9000;            server 192.168.18.191:9000;        }        ……       Server{         listen        80;         server_name   load.onmpw.com   ##这里是域名         root           /www/onmpw                  ……         location ~ \.php$ {                   root         /www/onmpw   ##这里是PHP应用所在目录                   fastcgi_pass   onmpw_phpApps;                   ……         }      }}

以上是对Nginx进行的设置。其中只是包含了关键的部分,其余的和平常我们使用Nginx+PHP作为web服务的时候进行的设置相同。

PHP所在主机设置

这里的设置就比较简单了。

首先编辑php-fpm.conf文件,修改监听的ip和端口,然后启动fpm服务

主机192.168.5.112

Listen = 192.168.5.112:9000   //这里的端口可以自行设置。保存退出# /usr/local/php/sbin/php-fpm   //开启服务

主机192.168.5.113

Listen = 192.168.5.113:9000# /usr/local/php/sbin/php-fpm

到这里就对PHP的主机设置完成了。当然了,代码需要在两台主机上各上传一份儿。

好了,经过上面的设置,一个基本的PHP集群就已经搭建完成了。但是有一个问题,这种情况如果只是访问静态资源或者不进行交互的话是没有问题的。如果需要交互,那就涉及到一个session共享的问题。默认情况下PHP是将session存在本地磁盘上的。那这两台主机之间如何共享session呢,接下来我们就来解决这个问题。

PHP主机之间Session共享

之前在网上看到过一种解决方式。由于PHP是将session存储在文件中,那我们可以在Nginx负载主机上面搭建一个分布式文件系统(NFS),让两台PHP主机的session都存放在此文件系统中。以此来达到共享session的目的。

我个人比较倾向于将session存储到数据库中。因此这里我介绍的是将session存储到redis中。所以我们需要增加一台Redis服务器

Redis服务器:192.168.5.114

PHP默认情况下是不支持对Redis的操作的。所以这里我们需要自己手动安装第三方的扩展,使其支持对Redis的操作。关于如何使PHP支持Redis,我们可以参考《PHP操作Redis的两种方式》。

在这里我就认为我们的PHP已经支持Redis了。接下来是将session存储到Redis中,有两种方式:一种是直接修改PHP的配置文件php.ini;另一种是重写session机制。

修改PHP配置文件php.ini将session存储到Redis中

使用vim打开php.ini,需要修改的有这两项:session.save_handler和session.save_path。

session.save_handler = Redissession.save_path = “tcp://192.168.5.114:6379”//Redis不需要密码验证session.save_path = “tcp://192.168.5.114:6379?auth=password”//Redis 需要密码验证

修改完成,保存退出。然后重启php-fpm服务

# kill -INT `cat /usr/local/php/var/run/php-fpm.pid`# /usr/local/php/sbin/php-fpm

两台PHP主机都做按照以上步骤操作。经过以上步骤,对于session的所有信息都保存到了Redis中。从而实现了session的共享。

通过重写session机制将session存储到Redis中

通常,在很多情况下我们是没有权限修改php.ini文件的。这时候我们可以通过重写session机制来修改session信息的存储。

对于重写session,php已经为我们提供了SessionHandlerInterface 接口。我们只要实现这个接口就可以了。关于如何重写session机制,大家可以参考 《PHP重写session机制》 这篇文章。并且我自己也重写了session的机制,该类的完整代码在github上,大家有兴趣的和可以 点此查看 。

总结

PHP集群的架构方式有很多种,但是其原理都大同小异。关键是找出最适合自己项目的最佳方案。例如:对于session存储方式的选择,你也可以选择使用memcache或者MySQL数据库等。总之最适合自己的就是最优的。希望本文对大家有所帮助。

想阅读更多技术文章,请访问听云技术博客,访问听云官方网站感受更多应用性能优化魔力。

Statement
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools