Home Backend Development PHP Tutorial A detailed discussion of PHP distributed deployment

A detailed discussion of PHP distributed deployment

Jan 25, 2018 pm 02:14 PM
php distributed

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 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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles