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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

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 Tools

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!