Cache usage, caching using _php tutorial

Source: Internet
Author: User
Tags dsn pconnect

Cache usage, Cache usage


cache, to improve access speed of the weapon. The main use of the work is memcache and Redis, they are b/s software, similar to practice fashion on the machine Apache, it will also listen to the port, can be in the client (such as CMD on the memcache via Telnet operation) directly to the corresponding command to access the value, Self-study can be done in such a way familiar with the native command, see the effect. They reside in memory, get the data to write to memory (after installing the software will occupy a memory area), set the data expiration time, used to read directly from memory, because it is memory, so the speed of access to an order of magnitude increase. LZ Roost wrote a very simple backstage, completely do not cache that kind, that speed I saw the oneself can not help to roar: So slow TM also called Web page?! But I was young and foolish, will not use the cache, of course, now is not necessarily good where to go, I hope that the front-end sister did not secretly reviled in the heart >3<

The use of memcache is simple, at least from the command point of view. In Memcache, storage is stored in the same way as a key->value, a key-value corresponding to an element form of a join array, a type that can be stored as a number, a string, an array, an object, etc. In a project, a non-string (number can be considered a numeric string) type of advanced line JSON encoding or serialization is stored in the cache, and then decoded or deserialized when it is fetched. Memcache is a class that PHP specializes in dealing with memcache caches, and the main methods of encapsulation are get, set, delete, flush, connect, close, which is a cache prerequisite for getting, setting, deleting, emptying, connecting, shutting down, and so on. (The bracket is a parameter that can be passed)

Add Key, Var, [flag], [expire] Add a key to key, Var to server, specify expiration time expire,0 never expires, up to 30 days
Get Key, [flag] Get a certain or some element from the server
Delete Key, [timeout] Deletes the key corresponding element within the specified timeout time, and the default timeout is 0 delete immediately
Flush No Empty, i.e. delete all elements
Connect Host, [Port], [timeout] Port that is connected to the Memcache server host, which automatically shuts down after the script is executed, or can be actively shut down
Close No Proactively shuts down Memcache server connections, but does not shut down Pconnect-generated connections
Set Key, Var, [flag], [expire] The element that stores the key is key, the value is var to the server, the key exists to overwrite its value, there is no new add one
Replace Key, Var, [flag], [expire] Find keys key element, replace with value Var, do not check the error
Increment Key, [value] Add value on element key Value,value default is 1, may change the original value
Decrement Key, [value] Reduce the value on the element key value,value default is 1, may change the original value
Addserver Host, [port], [persistent], [weight], [timeout], ... Add a memcache service to the connection pool (where multiple memcache connections are saved), that is, establish a connection to host, port
Pconnect Host, [Port], [timeout] Establish a persistent connection to the host's Memcache server, port, the script finishes or call Close and cannot close the connection

Here are a few things to keep in mind:

1. The use of set and replace the difference: Set almost any case, of course, not the connection is unsuccessful, the memory is not enough for hard reasons, are successful, replace just in the existing keys based on the modification, if the key does not exist unsuccessful;

2. The Connect method establishes the connection, either the script runs out of its own disconnection, or the call to close () method is disconnected;

3. The number of increment or decrement method will always be greater than or equal to 0, if the calculated value is less than 0 of the conversion, such as the int type, 32 bits on the 4 bytes, then the return value is (232-1), the calculation is greater than or equal to 0 of the direct return While the element type is non-numeric (or numeric string), it is converted to a number and then calculated;

4. When we new a Memcache object and connect, there can be two ways, one is the Connect method: $mem =new Memcache; $mem->connect (' 127.0.0.1 ', 11211); Or use the Addserver method: $mem->addserver (' 127.0.0.1 ', 11211); The latter is created in a way that adds a Memcache server connection to an existing connection pool, with the same effect.

Redis, a powerful caching tool, thanks to the extensive use of domestic portals, functional in the continuous improvement, now has a stable version (seemingly Microsoft GitHub on the latest 64-bit release 2.8 version, in my work on the machine to run not up ... ), the method is much more than memcache, as the main use of the development of data access, and other things, communication protocols, clusters, in the general development of the background, not to the speed of the pursuit to the extreme situation, or basic use. There are several types of operations in Redis that are categorized as follows:

1. String: Also Key-value pair, mainly for its keys corresponding to the elements of Get, set, seek length, self-increment, and so on, Redis will add the type of all save as a string, even if the pure number;

  

2. Hash: Hash table (hash table), is the data structure of the dictionary, using a specific hashing algorithm, such as mobile phone address book has hundreds of people, with the first letter of the surname as the key code to sort, so we can quickly find the contact, which is through a specific mapping method, a letter with the name of the link. In Redis, when you create a hash table, you first specify the table name, which table you exist in, and then specify a field (field, which is actually a variable), and its corresponding value, with the CMD operation as follows (store a field username corresponding value in hash table Hash1) jack , Redis will automatically establish a map of username to Jack, and a hash table can store multiple fields and corresponding variables;

  

3. List: Lists, similar to the data structure of the linked list, through which can also implement stacks and queues, the preceding string (the name gets very weird) store one by one corresponding to a single key value pair, it is stored multiple values (no key), the focus is as a list structure, It can be inserted from the left and right (table header and footer) to insert and eject variable values, such as the length of a series of operations, which is also why called the list, the following lpush, Rpush command is from the left side of the table and the rights to insert variable Hello and world;

  

4. Set: Set, as the name implies can also store multiple variable values (no key), just conform to the characteristics of the mathematical definition of the set, such as the collection of elements are not duplicated, so the set of the individual data pairs of key names are not the same, it can also be done and, intersection, Bad operation (The following command is to add a value var to the collection MySet);

  

5. SortedSet: An ordered set, can be seen as a special way of set, in each SortedSet type collection, add a value (no key), you have to give them a variable value called score, ordered and ordered, there must be a field to determine its order is no, this thing, The following command creates an ordered collection Stset, adds a value of Google.com, and its score is 10. In fact, guess also guessed, since called ordered set, since given the score, the basic determination can use this to carry out some sort operation, the fact is this;

  

6. Key: The operation of the key alone, of course, its corresponding element value also has an impact, such as the data type of the corresponding element of the view key, the key corresponds to the element's survival time, reset the survival time, return all keys, the regular form to view the key name, delete the key (the element is not followed) and so on. It is not a data type, and in fact, Redis refers to the hash table name, List table name, and set set names as keys, and the entire set or table is its value. The following is the type command to see if it stores a worthwhile type, which stores a list of lists.

  

Above these commands, find a reference document to go through, soon to play ripe, the individual here is only a generalities. So how do you usually use caching in a real-world project? Not big talk, such as the Twitter cache design, this may involve architectural aspects of things, such as a certain amount of traffic in the background, but also want to use the cache to increase the speed of the case.

An important principle (the individual currently touches a lot of cases) is to use the input parameters to spell the key name , the key name to access the value . For example, there is a method in the Model class: Getuserinfobyuid ($params), passing in an array that contains the UID field to query the user's information, use the cache here, first fetch the cached data, then go to the database, then re-join the cache, and finally return the result data, This is also a common process for using caching.

Take Memcache as an example, first look at the code, define a cache class:

    /** * Memcache Cache class*/    Define(' Cache_host ', ' 127.0.0.1 '); Define(' Cache_port ', 11211); classcache{Private Static $instance=NULL; Private $_cache=NULL;//Cache Action Object                Constprefix = ' app| ';//The prefix for the cache key value, for the project name                Private function__construct () {if($this->_cache = = =NULL){                Try{                    $this->_cache =NewMemcache; if(!$this->_cache->connect (Cache_host,Cache_port)) {                        Exit(' Connect failed '); }                                    }                Catch(Exception $e){                    Echo' ERROR: '.$e-GetMessage (); }                            }        }        /** * Return to Singleton*/         Public Static functiongetinstance () {if(Self::$instance===NULL) { self::$instance=NewSelf (); }            returnSelf::$instance; }        /** * Generate Key Name*/        Private functionGenkey ($key){            returnCache::p Refix.$key; }                 Public function__destruct () {if($this->_cache!==NULL){                return $this->_cache->Close (); }        }        /** * add element, set expiration time*/         Public functionAdd$key,$val,$expire= 3600){            return $this->_cache->add ($this->genkey ($key),$val, 0,$expire); }        /** * Reset elements*/         Public functionSet$key,$val,$expire= 3600){            Echo' Cache key: '.$this->genkey ($key).'
';//Test return $this->_cache->set ($this->genkey ($key),$val, 0,$expire); } /** * Get elements*/ Public functionGet$key){ return $this->_cache->get ($this->genkey ($key)); } /** * Self-increment*/ Public functionIncrement$key,$val= 1){ return $this->_cache->increment ($this->genkey ($key),$val); } /** * Self-reduction*/ Public functionDecrement ($key,$val= 1){ return $this->_cache->decrement ($this->genkey ($key),$val); } /** * Delete element*/ Public functionDelete$key,$timeout= 0){ return $this->_cache->delete ($this->genkey ($key),$timeout); } /** * Delete all elements*/ Public function Flush(){ return $this->_cache->Flush(); } }

Then define an operational database action class:

    /** * Database Operation*/    Define(' db_name ', ' Test '); Define(' Db_host ', ' 127.0.0.1 '); Define(' Db_port ', 3306); Define(' Db_user ', ' root '); Define(' Db_pass ', ' 1234 '); classdal{Private Static $instance=NULL;  Public $pdo=NULL; Private function__construct () {Try{                $dsn= ' mysql:dbname= '. Db_name. '; Host= '. Db_host. ': '.Db_port; $this->pdo =NewPDO ($dsn, Db_user,Db_pass); }            Catch(pdoexception$e){                Echo' Error: '.$e-GetMessage (); return false; }        }        //Get Instance         Public Static functiongetinstance () {if(Self::$instance===NULL) { self::$instance=NewSelf (); }            returnSelf::$instance; }        //Get user Information         Public functionGetuserinfobyuid ($uid){            $sql=sprintf(' select * from tab1 where uid =%s Limit 1 ',$uid); $stmt=$this->pdo->query ($sql); return $stmt->fetch (PDO::FETCH_ASSOC); }    }

In general, the data is usually read and written in the model class, so define a Usermodel class that is as simple as possible and no longer writes the possible model public public base class.

    include' Dal.php '; include' Cache.php '; classusermodel{Private Static $instance=NULL;  Public $cache=NULL;  Public $db=NULL; //cache Key Name section, by function name and parameter stitching        ConstCache_get_userinfo_uid = ' get| user|info| by| uid|%s '; Private function__construct () {//get the corresponding class instance            $this->cache = cache::getinstance (); $this->db = Dal::getinstance (); }                 Public Static functiongetinstance () {if(Self::$instance===NULL) { self::$instance=NewSelf (); }            returnSelf::$instance; }                /** Obtain user information according to UID*/         Public functionGetuserinfobyuid ($params,$timeout= 3600){            //missing necessary parameter uid, return            if(Empty($params[' UID '])){                return NULL; }                //splicing Cache Key Name            $key=sprintf(Self::cache_get_userinfo_uid,$params[' UID ']); //Get Cached Data            $data= Json_decode ($this->cache->get ($key),true); Echo' Cache=>
'; Var_dump($data); //Cache is empty            if(!$data){                $data=$this->db->getuserinfobyuid ($params[' UID ']); if(Empty($data)){                    return NULL; }                //after data is fetched in the database, the cache is re-written                $this->cache->set ($key, Json_encode ($data),$timeout); }            Else{                            }            return $data; }    }    //Test    $data= Usermodel::getinstance ()->getuserinfobyuid (Array(' uid ' =>17653), 5); Echo' Usermodel=>
';     Var_dump ($data);

Here, we want to pass the user's UID to obtain a user's information, this query condition is UID, pass over the necessary parameter is UID, originally we are to cache each user's data, in order to repeat the query faster, so in the definition of the cache key, you can consider the use of UID. But the use of this UID alone is not possible, because if other tables are also based on the UID query, there will be duplicate key names, resulting in data confusion, good we use getuserinfobyuid this method, you can put the method name is also spelled in, so in the Usermodel class, A constant cache_get_userinfo_uid is defined, and its last%s is to splice the parameter UID. However, this may still not work, and now the company started another project, but also to use this table, someone to write the method with the method name exactly the same, after all, the function name is not patented, and operations generally take the server out as a cache use, several projects public one server, the data written in a buffer pool is also normal, At this point you can consider adding a prefix---project name (or project), so in the cache class, also defined a constant prefix, to the project called the app, so that the basic can guarantee that there will be no conflict. Of course if this is a group of sub-projects, this group has other projects, this group is called Star, you can add the project group name in front.

Look at the effect, the first time (left) to run the read cache is empty, but you can see the print cache key name,

  

The second (right) cache has data, because I put the print cache key name in the cache class in the Set method, the second time directly read the cache data, not to connect the database, and naturally did not reset the cache, so did not print cache key.

Pull a long way is to ensure that the key name does not conflict, but also mixed with the general in a project how to use the cache, there are several ways to refer to:

1. Current parameters, can have a few splicing several, here only a UID, if there is name, age and so on, can be put in the back, how to see a person likes or code specification;

2. The current method name, as close as possible to the current method name, spell in the middle of the cache key;

3. The current project name as a prefix (optional), more secure;

4. The project group name, again as a prefix to enter (generally not used).

Then, in the model class, take the cache first, not the read database, read after the write cache, set the expiration time and other details, such a process.

Of course you can also do more meticulous, such as reading to the cache data, then detect its expiration time, found that there are 5 seconds to expire, so we re-set it to 3,000 seconds, so that the next visit can be taken, not the next time to read the library, frequent connection to the database is a very time-consuming thing.

But I still think that Redis is good, the hash table in Redis is the best >-_-<, but it just doesn't fit on the machine.

Well...... It's not early, wash and sleep ~=_=

http://www.bkjia.com/PHPjc/950709.html www.bkjia.com true http://www.bkjia.com/PHPjc/950709.html techarticle Caching is used, caching is used to improve access speed. The main use of the work is memcache and Redis, they are b/s software, similar to the practice of fashion on the machine Apache, it ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.