search
HomeBackend DevelopmentPHP TutorialA detailed discussion of PHP distributed deployment

In this article, we will share with you PHP distributed deployment, hoping that everyone will have a clearer idea about PHP distributed deployment.

In ordinary Web development, the common mode is that after the user logs in, the login status information is stored in the Session, some of the user's commonly used hot data is stored in the file cache, and the attachment information uploaded by the user is stored in a certain location of the Web server. on a directory. This method is very convenient to use and fully capable for general Web applications. But for high-concurrency enterprise-level websites, it cannot handle it. Web clusters need to be used to achieve load balancing.

After deploying using the Web cluster method, the first thing to adjust is the user status information and attachment information. User status can no longer be saved to the Session, the cache cannot use the file cache of the local Web server, and attachments cannot be saved on the Web server. Because it is necessary to ensure that the status of each web server in the cluster is completely consistent. Therefore, user status, cache, etc. need to be saved to a dedicated cache server, such as Memcache. Attachments need to be saved to cloud storage, such as Qiniu Cloud Storage, Alibaba Cloud Storage, Tencent Cloud Storage, etc.

This article takes the ThinkPHP development framework as an example to explain how to set up and save Session, cache, etc. to the Memcache cache server.

Download the cached Memcache processing class and place it in the Thinkphp\Extend\Driver\Cache directory; download the Session Memcache processing class and place it in the Thinkphp\Extend\Driver\Session directory. As shown in the figure below:




# Modify the configuration file, adjust the Session and cache, All are recorded on the Memcache server. Open ThinkPHP\Conf\convention.PHP and add configuration items:




##[ php]

view plain copy


  1. ##/* Memcache cache settings */

  2. 'MEMCACHE_HOST'

    => '192.168.202.20',

  3. ##'MEMCACHE_PORT'
  4.                                                                                                                ## Modify the data cache to Memcache:



    [php] view plain copy


    1. ##'DATA_CACHE_TYPE'   => 'Memcache' ,

    ## Modify Session to Memcache:





    ##[php]

    view plain copy


      ##'SESSION_TYPE'
    1.     => 'Memcache' ,

    As shown below:



    Because there are many types of cloud storage, attachments are stored on cloud storage, so I won’t go into details. Just parameterize the SDK provided by each cloud storage. After the above modifications, the Web server can be deployed in a distributed manner.


    ## Attachment 1: CacheMemcache.class.php



    [php]

    view plain copy

    1. // +----------------------------------------------------------------------  

    2. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]  

    3. // +----------------------------------------------------------------------  

    4. // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.  

    5. // +----------------------------------------------------------------------  

    6. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )  

    7. // +----------------------------------------------------------------------  

    8. // | Author: liu21st   

    9. // +----------------------------------------------------------------------  

    10.   

    11. defined('THINK_PATH') or exit ();

    12. ##/**

    13. ## * Memcache cache driver

    14. * @category Extend

    15. ## * @package Extend

    16. * @subpackage Driver.Cache

    17. ## * @author liu21st
    18. */
    19. ##class
    20. CacheMemcache

      extends Cache {

    21. /**
    22. * Architectural function
    23. ## * @param array $options Cache parameters

    24. * @access public

    25.      */  

    26.     function __construct($options=array()) {  

    27.         if ( !extension_loaded('memcache') ) {  

    28.             throw_exception(L('_NOT_SUPPERT_').':memcache');  

    29.         }  

    30.   

    31.         $options = array_merge(array (  

    32.             'host'        =>  C('MEMCACHE_HOST') ? C('MEMCACHE_HOST') : '127.0.0.1',  

    33.             'port'        =>  C('MEMCACHE_PORT') ? C('MEMCACHE_PORT') : 11211,  

    34.             'timeout'     =>  C('DATA_CACHE_TIMEOUT') ? C('DATA_CACHE_TIMEOUT') : false,  

    35.             'persistent'  =>  false,  

    36.         ),$options);  

    37.   

    38.         $this->options      =   $options;  

    39.         $this->options['expire'] =  isset($options['expire'])?  $options['expire']  :   C('DATA_CACHE_TIME');  

    40.         $this->options['prefix'] =  isset($options['prefix'])?  $options['prefix']  :   C('DATA_CACHE_PREFIX');          

    41.         $this->options['length'] =  isset($options['length'])?  $options['length']  :   0;          

    42.         $func               =   $options['persistent'] ? 'pconnect' : 'connect';  

    43.         $this->handler      =   new Memcache;  

    44.         $options['timeout'] === false ?  

    45.             $this->handler->$func($options['host'], $options['port ']) :

    46. ##                                                                                ##$func($options['host'], $options['port'], $options[' timeout']); ## }

    47. /**

    48. ## * Read cache

    49. ## * @access public

    50. * @param string $name cache variable name

    51. ## * @return mixed

    52. ## */

    53. ##public

      function get( $name) {

      ## N(
    54. 'cache_read'
    55. ,1 ; handler->get($this->options['prefix'

    56. ].
    57. $name ); ## } #                                                                                              

    58. # * @access public

    59. * @param string $name Cache variable name

    60. ## * @param mixed $value Stored data

  5.      * @param integer $expire  有效时间(秒) 

  6.      * @return boolen 

  7.      */  

  8.     public function set($name$value$expire = null) {  

  9.         N('cache_write',1);  

  10.         if(is_null($expire)) {  

  11.             $expire  =  $this->options['expire'];  

  12.         }  

  13.         $name   =   $this->options['prefix'].$name;  

  14.         if($this->handler->set($name$value, 0, $expire)) {  

  15.             if($this->options['length']>0) {  

  16.                 // 记录缓存队列  

  17.                 $this->queue($name);  

  18.             }  

  19.             return true;  

  20.         }  

  21.         return false;  

  22.     }  

  23.   

  24.     /**

  25. ## * Delete cache

  26. * @access public

  27. ## * @param string $name cache variable name

  28. * @return boolen

  29. ##*/

      

  30.     
  31. public

     function rm($name$ttl = false) {  

  32.         
  33. $name

       =   $this->options['prefix'].$name;  

  34.         return $ttl === false ?  

  35.             $this->handler->delete($name) :  

  36.             $this->handler->delete($name$ttl);  

  37.     }  

  38.   

  39.     /**

  40. * clear cache

  41. * @access public

  42. # * @return boolen

  43. */  

  44.     public function clear() {  

  45.         return $this->handler->flush();  

  46.     }  

  47. }  

  附件2:SessionMemcache.class.php




[php] view plain copy


  1. // +----------------------------------------------------------------------  

  2. // |   

  3. // +----------------------------------------------------------------------  

  4. // | Copyright (c) 2013-   

  5. // +----------------------------------------------------------------------  

  6. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )  

  7. // +-------------------------------- -------------------------------------

  8. ##// | Author: richievoe

  9. ##// +----------------------------------- ----------------------------------

  10. ##​
  11. /**

  12. ## * Customize Memcache to save session
  13. */
  14. ## Class SessionMemcache{

  15. ##//memcache object

  16. private

  17. $mem; #//SESSION valid time

  18. ##private

  19. $expire

    ; ##//Externally called functions

  20.     public function execute(){  

  21.         session_set_save_handler(  

  22.             array(&$this,'open'),   

  23.             array(&$this,'close'),   

  24.             array(&$this,'read'),   

  25.             array(&$this,'write'),   

  26.              array(&$this,'destroy'),                                                        ,

    'gc'
  27. )

    #                                                              ## } } ##   //Connect memcached and initialize some data

  28. public

  29. function
  30. open($ path,$name

  31. ){
  32. ##            $this ->expire = C('SESSION_EXPIRE') ? C('SESSION_EXPIRE') :ini_get

    (
  33. 'session.gc_maxlifetime'

    );

  34. ##                                                                                                                   #              return $this

    ->mem->connect(C(
  35. 'MEMCACHE_HOST'

    ), C('MEMCACHE_PORT')); }    

    //Close memcache server
  36.  

  37. public function

    close(){
  38. ##                                                                                                                                            }  

  39. ##    

    //Read data   public

  40. function read(

  41. $id
  42. ){

  43.         $id = C('SESSION_PREFIX').$id;  

  44.         $data = $this->mem->get($id);  

  45.         return $data ? $data :'';  

  46.     }  

  47.     //存入数据  

  48.     public function write($id,$data){  

  49.         $id = C('SESSION_PREFIX').$id;  

  50.         //$data = addslashes($data);  

  51.         return $this->mem->set($id,$data,0,$this->expire);  

  52.     }  

  53.     //销毁数据  

  54.     public function destroy($id){  

  55.         $id = C('SESSION_PREFIX').$id;  

  56.              return $this->mem->delete ($id);

  57. ## }

  58. //Garbage destruction

  59. ## public function gc(){

  60. # true; ## }

  61. }

  62. ?>

  63. #Related recommendations:

PHP distributed tracing experience sharing

Issues related to PHP distributed and large-scale data processing

php distributed architecture

The above is the detailed content of A detailed discussion of PHP distributed deployment. For more information, please follow other related articles on the PHP Chinese website!

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's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function