Data caching:
With the development of Internet technology, the bottleneck of network speed is mainly focused on access distance and server load capacity.
An extended server or mirror server is expensive to operate and maintain as a basic solution,
As a supplementary scheme, cache caching technology has been widely used for its simple design and efficient storage performance.
Memcache is a more popular cache solution, is an efficient and fast distributed memory object caching system, mainly for the acceleration of WEB dynamic applications
What's memcache?
Memcache is a danga.com project, the first to serve the LiveJournal, many people around the world use this cache project to build their own heavy load of the site to share the pressure of the database.
The working mechanism of memcache
It works by opening a space in memory and then creating a hashtable,memcached to manage these hashtable.
Why there are memcache and memcached two kinds of names.
In fact Memcache is the name of this project, and memcached is its server-side main program filename
Memcached is the server-side program name that is running on the cache servers.
Memcache is the client side of Memcache server, with a variety of language versions, such as Java, PHP, etc.
Memcache server can be viewed as a DB server,
Memcache not have to be installed with Apache on the same server, and Apache can be installed together to make full use of resources, Apache occupies more than CPU, memory is relatively small, and memcache occupy CPU low, memory more.
The installation of Memcache is divided into two pieces:
Memcache Server-side installation
Memcache Client Installation
The so-called server-side installation is on the server (typically Linux system) on the installation of Memcache implementation data storage
The so-called client installation refers to adding extensions for PHP, such as the function provided by the server-side memcache after the Php_memcache.dll,apache is started.
To install memcache under Windows:
Client Memcache.dll support php5.2, put it in the Ext directory of PHP, php.ini add a sentence extension=php_memcache.dll can be.
There is a memcached.exe after the service side decompression.
In DOS, switch to directory:
Memcached.exe-d install is installed as a system service for Windows.
You can then start and close the memcached in the service,
It can also be opened with memcached.exe-d start under DOS.
The default port number is: 11211.
The sign of the memcache is the donkey:
To Baidu Google search to your current memcache version of the relative Php_memecache.dll
Copy to ext/after download
Find extension in the back of it to increase
Extension=php_memcache.dll
; A high-performance distributed Memory object caching system that maintains a unified, huge hash table in memory
; It can be used to store data in a variety of formats, including images, videos, files, and the results of database retrieval.
; Whether to transparently failover to other servers when an error is encountered.
Memcache.allow_failover = On
; The maximum number of servers to try when accepting and sending data, only when opening memcache.allow_failover.
Memcache.max_failover_attempts = 20
; The data is transferred according to the block size set by this value. The smaller the value, the more network traffic is required.
; If you find an unexplained rate decrease, you can try to increase this value to 32768.
Memcache.chunk_size = 8192
; The default TCP port to use when connecting to the memcached server.
Memcache.default_port = 11211
Let PHP support Memcache
Restart Apache
Open Phpinfo ();
If you appear
Memcache
Memcache Support Enabled
Active Persistent Connections 0
Version 2.2.4-dev
Revision $Revision: 1.99 $
Directive Local value Master value
Memcache.allow_failover 1 1
Memcache.chunk_size 8192 8192
Memcache.default_port 11211 11211
Memcache.hash_function CRC32 CRC32
Memcache.hash_strategy Standard Standard
Memcache.max_failover_attempts 20 20
Indicates memcache installation is successful!
Memcached
Default port 11211 for Memcache
MySQL database default port 3306
Apache Default Port 80
$memcacheOBj->connect ("Memcache server name", port);
Long connection Pconnect ("Memcache server name", port);
Add a censored Check
Add (Key,value,bool,time); Returns False if key already exists, and returns true if successful
Set (Key,value,bool,time);
Parameter explanation:
Key: Keys are used to locate a data
Value: The data content to be saved
BOOL: compression: usually false
Time: The expiration date of the current storage data, that is, the data is valid at this time, if the past this time, then will be Memcache server side to clear the data, unit is seconds, if set to 0, is always valid
Get (key); Returns the value of the key, and the data type of the key can be an array letter
Replace
Replace (Key,value,bool,time), replacing a value that already exists a key
Delete
Delete (key,time); Parameter explanation: Time indicates how long after the deletion if it is 0 that means to delete immediately
Clear All data
$mem->flush (); Indicates empty cache
Close connection
$mem->close ();
Instance:
Link
<?php
/**
* @author Phpadmin
* @copyright 2012
*/
$memcacheOBj =new Memcache ();
$conn = $memcacheOBj->connect (' localhost ', 11211) or Die (' Memcahce server Connection failed ');
if ($conn) {
Echo ' MEMCAHCE server connection succeeded ';
}
?>
Multiple Server server connections
Add to
<?php
/**
* @author Phpadmin
* @copyright 2012
*/
$mem =new Memcache ();
$conn = $mem->connect (' 127.0.0.1 ', 11211) or Die (' Memcache connection failed ');
if ($conn) {
$result = $mem->set (' Test ', ' Huayu International Lmap25 class ');
if ($result) {
$value = $mem->get (' Test ');
Echo $value;
}
}
?>
Modify
<?php
/**
* @author Phpadmin
* @copyright 2012
*/
$mem =new Memcache ();
$conn = $mem->connect (' 127.0.0.1 ', 11211) or Die (' Memcache connection failed ');
if ($conn) {
$tmp = $mem->replace (' Test ', ' I'm going to change, you read it out to see ');
if ($tmp) {
echo $mem->get (' Test ');
}
}
?>
Data caching and application of MySQL
<?php
/**
* @author Phpadmin
* @copyright 2012
*/
$conn =mysql_connect (' localhost ', ' root ', ');
mysql_select_db (' memcache ');
Mysql_set_charset (' UTF8 ');
/**
* Practical application in the project
* Query the database before querying whether there is a cache if no more query the database
-*/
$mem =new Memcache ();
$tmp = $mem->connect (' 127.0.0.1 ', 11211) or Die (' Memcache connection failed ');
$query = ' SELECT * from mytest ORDER by id DESC ';
if ($tmp) {
$value = $mem->get (' $query ');
if ($value) {
Echo ' <pre> ';
Print_r ($value);
Echo ' </pre> ';
Echo ' Memcache ';
}else{
$result =mysql_query ($query);
while ($rows =mysql_fetch_assoc ($result)) {
$values []= $rows;
}
$return = $mem->set (' $query ', $values);
if ($return) {
Echo ' <pre> ';
Print_r ($values);
Echo ' </pre> ';
echo ' SQL ';
}
}
}
?>
Encapsulating database query function +MEMCAHCE---
To implement this Function procedure:
Function name: query ()
Parameters: SQL Dblink memcache Isflush
The process of implementation:
1. Do you need to update
2. Is---> query database---> Write memcache--return Data
3. No----> whether the cache exists---> is-----> Query memcahe--return Data
No-----> Query Database--> write memcache--> return data
Application Scenario:
Forum----> on issues---2000/s concurrency
-----Implement the data caching architecture;
Implement the basic logic of the application:
Alternate caching and data operations according to the time high bottom peak
1. All writes or reads from the current user are written to multiple Memcahe servers according to the group, topic, and Time end
2. Import memcache data into the database
The realization of-----shopping cart-----
Users add shopping Cart---> Write cache--->---> Place the contents of the order into a database operation----> write to the user's shopping list (modify inventory items)
--------------> Write the data inside the memcache to the database when the server is not busy
---> Shopping cart----> will memcache and the database Inside Out
There are a lot of people in the list, and there are bottlenecks in the database.
The use of Memcache
Use Memcache Web site general traffic is relatively large, in order to ease the pressure of the database, so that memcache as a cache area, the part of the information stored in memory, the front-end can be accessed quickly. So the general focus is on how to share the database pressure and distributed, after all, the single memcache memory capacity of the limited.
Distributed applications
Memcache originally supported the distributed, our client slightly modified, better support. Our key can be properly packaged in a regular way, for example, user-oriented Web sites, each users have user ID, you can follow a fixed ID for extraction and access, such as 1 of users at the beginning of the first memcache server, The data of the user starting with 2 is stored on the second Mecache server, and the access data is converted and accessed according to the user ID first.
The above is just a simple example. In the actual work according to their actual business to consider, or to think of a more appropriate method.
Reduce database pressure
This is more important, all the data are basically kept in the database, every time the frequent access to the database, resulting in a very degraded database performance, can not serve more users at the same time, such as MySQL, particularly frequent lock table, so let memcache to share the pressure of the database. We need a way to change the current architecture by making small changes that will not change the front end on a large scale.
The memory of one server is very small, the 10 100 servers are big.
So you can link a lot of servers, and then distribute the data evenly (like playing poker)
Initializes an Memcache object:
$mem = new Memcache;
$mem->connect ("192.168.0.200", 11211);
$memcache->addserver (' Memcache_host ', 11211);
$memcache->addserver (' Memcache_host2 ', 11211); When it comes to keeping memcache open.
Add data to the inside and go to the same server to see what data is stored in the memcache.
Memcache hit rate
Cache Hit Ratio = Get_hits/cmd_get * 100% (Total hits/total requests)
To increase the hit rate of memcached, it is necessary to estimate our value size and adjust the memory page size and growth factor appropriately.
The increase in hit rate can be achieved through a variety of scenarios.
First, increase the amount of memory that the service gets
Second, improve space utilization, which is actually another way to increase the total amount of memory
Third, apply one level to another LRU
Four, for the overall hit rate, can take effective redundancy strategy, reduce the distributed service when a server occurs service jitter
Some attention
1. Memcache already allocated memory will not be actively cleaned up.
2. Memcache allocated to a slab page of memory can no longer be allocated to other slab.
3. Flush_all cannot reset the pattern of memcache allocated memory pages, just to expire all of the item.
4. Memcache Maximum storage item (key+value) size is limited to 1M, which is limited by page size 1M
5. Because the memcache is distributed by the client program through the hash algorithm to achieve the key, different languages may use different hash algorithm, the same client program may also use dissimilar methods, so in multi-language, multiple modules share the same group of memcached services, Be sure to choose the same hash algorithm on the client
6. You can disable LRU substitution with the-m parameter when you start memcached, and the add and set will return failure when memory runs out
7. The memcached specifies the amount of data storage when it starts, and does not include the memory that is consumed by itself, and the administrative space set up to save the data. As a result, it consumes more memory than is specified at startup, which requires attention.
8. Memcache storage When the length of the key is limited, PHP and c the maximum length is 250