Home >Backend Development >PHP Tutorial >Introduction and application of debugging methods in PHP using Memcache
Introduction and application of debugging methods in
If we are in network development, especially in the development of large-traffic
1. under linux
1.Download the
2. Install
1.
Download the memcache stable version of windows, unzip it and put it under a certain disk, such asc:memcachedmemcached.exe -d install
In the future,
4.Download
'
if there is
-p
service
-d restart Restart
Service
service
service
Only run as
-m
64MB
-f Block size growth factor, the default is
48
-h Display help
A high-performance distributed memory object cache system, by maintaining a unified huge Whether to transparently failover to other servers when errors are encountered. memcache.allow_failover = On The maximum number of servers to try when accepting and sending data. It is only valid when Data will be transferred according to the block size set by this value. Smaller values require more additional network traffic. If you notice unexplained slowdowns, you can try increasing this value to memcache.chunk_size = 8192 The default memcache.default_port = 11211 Controls the strategy of mapping is set to memcache.hash_strategy = "standard"; Controls the hash function that maps memcache.hash_function = "crc32" memcache can also be used as the storage module of 1 . $memcache = new Memcache; 2. $memcache->connect('localhost', 11211) or die ("Could not connect"); 3. 4. $version = $memcache-> getVersion(); 5. echo "Server's version: ".$version." 6. 7. $tmp_object = new stdClass; 8. $tmp_object- >str_attr = 'test'; 9. $tmp_object->int_attr = 123; 10. 11. $memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server"); 12. echo "Store data in the cache (data will expire in 10 seconds) 13. 14. $get_result = $memcache- > get('key'); 15. echo "Data from the cache: 16. 17. var_dump($get_result); We have installed and configured it Now that you have for a test. Make a table first: create table t(id char(36) not null primary key, username varchar(20) not null); Insert some data: insert into t values (uuid(),' Livia'),(uuid(),'Lucy'),(uuid(),'Sivia'),(uuid(),'david'); Write a simple script to test it. $host = '192.168.1.21:3306'; $user = 'webuser'; $passwd = '123456'; $db = 'test'; $conn = mysql_connect($host,$user,$passwd); mysql_select_db($db,$conn); $sql = 'select * from t order by id desc'; $result = mysql_query($sql,$conn); while ($row = mysql_fetch_array($result,MYSQL_ASSOC)){ $test_key[] = $row; } $sql = md5($sql); $mem = new Memcache; $mem->connect("192.168.1.21", 11211); $mem->set($sql,$test_key, MEMCACHE_COMPRESSED, 600); print_r($mem->get($sql)); ?> 看看结果出来了。 C:>php -f "d:/lamp/web2/phpinfo.php" Array ( [0] => Array ( [id] => d8f1ec2a-c033-11dd-bd1a-002215c94322 [username] => david ) [1] => Array ( [id] => d8f1eb9e-c033-11dd-bd1a-002215c94322 [username] => Sivia ) [2] => Array ( [id] => d8f1ea9a-c033-11dd-bd1a-002215c94322 [username] => Lucy ) [3] => Array ( [id] => d8f1e658-c033-11dd-bd1a-002215c94322 [username] => Livia ) ) 现在我们已经介绍 Memcache::add // 添加一个值,如果已经存在,则返回 Memcache::addServer // 添加 Memcache::close // 关闭一个 Memcache::connect // 打开一个到 Memcache::decrement // 对保存的某个 Memcache::delete // 删除一个 Memcache::flush // 刷新所有 Memcache::get // 从 Memcache::getExtendedStats // 获取进程池中所有进程的运行系统统计 Memcache::getServerStatus // 获取运行服务器的参数 Memcache::getStats //获取当前 Memcache::getVersion // 返回运行的 Memcache::increment // 对保存的某个 Memcache::pconnect // 打开一个到 Memcache::replace // 替换一个已经存在 Memcache::set // 向 Memcache::setCompressThreshold // 对大于某一大小的数据进行压缩 Memcache::setServerParams // 在运行时修改服务器的参数 下面是一些简单的用法实例,仅供参考: $mem = new Memcache; $mem->connect("127.0.0.1", 12000); //Memcache::set method has four parameters, the first parameter is $mem->set('test','123',0,60); //Memcache::add method is similar to $mem->add('test','123',0,60); //The function of the get method is to get a $mem->get('test');//The output is //Memcache::replace The function of the method is to replace an existing $mem->replace('test','456',0,60); //Memcache::deletemethod is to delete a $mem->delete('test',60); ?> Xiao Chenghu PHP caching application: PHP MEMCACHE detailed explanation 2010-01-28 09:38:44 Source: China Station Comprehensive long website [Large, Medium, Small] Comments: 0 I want to contribute, collect this article, share to Weibo Webmaster trading (http://jy.chinaz.com) helps webmasters make money, virtual host evaluation + IDC navigation = IDC123. COM Memcache function library is in PECL (PHP Extension Community Library). Its main function is to build a temporary storage area for large-capacity memory data. It is very obvious when it is distributed. Otherwise, it is not recommended to use it. After installing and running on ubuntu, an error occurs: Follow the method in "libeven, memcached, libmemcache installation", use: sudo ln -s /usr/local/lib/libevent-1.4.so.2 /usr/lib/libevent-1.4.so.2 This BUG can be fixed Install the memcached module of php through Xindeli, and unregister the "in /etc/php5/conf.d/memcached.ini" ;", restart apache, and call phpinfo() to display memcached information. 1. 2. $memcache = new Memcache; 3. $memcache->connect('localhost', 11211) or die ("Could not connect"); 4. print_r($memcache->getStats()); 5. /** 6. * Array 7. * ( 8. * [pid] => 8052 9. * [uptime] => 9205 10. * [time] => 1205898428 11. * [version] => 1.2.5 12. * [pointer_size] => 32 13. * [rusage_user] => 0.008000 14. * [rusage_system] => 0.000000 15. * [curr_items] => 1 16. * [total_items] => 17 17. * [bytes] => 57 18. * [curr_connections] => 2 19. * [total_connections] => 15 20. * [connection_structures] => 3 21. * [cmd_get] => 9 22. * [cmd_set] => 23 23. * [get_hits] => 5 24. * [get_misses] => 4 25. * [evictions] => 0 26. * [bytes_read] => 671 27. * [bytes_written] => 850 28. * [limit_maxbytes] => 10485760 29. * [threads] => 1 30. * ) 31. */ 32. ?> PHP caching application: PHP MEMCACHE Detailed explanation (2) 2010-01-28 09:38:44 Source: China Webmaster Comprehensive [Large, Medium, Small] Comments: 0 I want to contribute. Collect this article and share it on Weibo Webmaster Trading (http://jy.chinaz.com) helps webmasters make money Virtual host evaluation + IDC navigation = IDC123.COM memcached service is officially launched It is recommended to use an object-oriented approach to test this library: The Memcache::getVersion method is used to return the version information of the running Memcache. The function of the Memcache::getStats method is to return some running statistics of the server. The Memcache::getStats method has three parameters. The first parameter indicates the requested return type: reset, malloc, maps, cachedump, slabs, items, sizes; the second parameter and the third parameter are set in the first parameter. cachedump". The Memcache::getExtendedStats method is used to obtain the running system statistics of all processes in the process pool. The memcache_debug() function is used to control the debugging function. The premise is that the –enable-debug option is used when php is compiled, otherwise this function will not have any effect. The Memcache::addServer method is used to add a server address that can be used. The Memcache::addServer method has 8 parameters. Except for the first parameter, the others are optional. The first parameter indicates the server. The address, the second parameter indicates the port, the third parameter indicates whether it is a persistent connection, the fourth parameter indicates the weight of this server among all servers, the fifth parameter indicates the duration of the connection, and the sixth parameter indicates The first parameter represents the interval between connection retries. The default is 15. Setting it to -1 means no retry. The seventh parameter is used to control the online status of the server. The eighth parameter allows setting a fallback function to handle error messages. . The Memcache::setServerParams method is used to modify the parameters of the server at runtime. The Memcache::setServerParams method has six parameters, and the Memcache::addServer method is missing the third and fourth parameters. The Memcache::getServerStatus method is used to obtain the parameters of the running server. The two parameters represent the address and port respectively. The Memcache::flush method is used to clear all cached data, but it will not reduce the used memory space. The Memcache::increment method is used to add the value in a saved key, and the Memcache::decremen method is used to subtract the value in a saved key. PHP MEMCACHE advanced cache application detailed explanation Article entry: 7747.Net Responsible editor: 7747.Net 269 [Font: Small Large] Memcache function library is in PECL (PHP Extension Community Library). Its main function is to build a temporary storage area for large-capacity memory data. Its effect is very obvious when it is distributed, otherwise it is not recommended to use it. When I installed on Ubuntu, I reported an error: cannot open shared object file: No such file or directory Follow the method in "libeven, memcached, libmemcache installation", use: sudo ln -s /usr/local/lib/libevent-1.4.so.2 /usr/lib/libevent-1.4.so .2 Install the memcached module of php through Xindeli, unregister the ";" in /etc/php5/conf.d/memcached.ini, restart apache , and call phpinfo() to display memcached Information Execution: $memcache = new Memcache; /usr/local/bin/memcached -d -m 10 -u root -l 127.0.0.1 -p 11211 -c 256 -P Memcache::add — Add a value, if it already exists, return false It is recommended to use oriented Object method to test this library: Memcache::getVersion method is used to return the version information of running Memcache. Memcache::getStats The function of the method is to return some running statistics of the server. The Memcache::getStats method has three parameters. The first parameter indicates the type of return required: reset, malloc, maps, cachedump, slabs, items, sizes; the second parameter and the third parameter are in the third parameter. Used when a parameter is set to "cachedump". The function of the Memcache::getExtendedStats method is to obtain the running system statistics of all processes in the process pool. Memcache::connect method is used to create a Memcache object. The Memcache::pconnect method is used to create a Memcache persistent connection object. The Memcache::close method is used to close a Memcache object. The function of the Memcache::set method is to add a value. The Memcache::set method has four parameters. The first parameter is key, the second parameter is value, and the third parameter is optional, indicating whether Compressed save, the fourth parameter is optional, used to set a time for automatic destruction after expiration . The Memcache::add method is similar to the Memcache::set method. The difference is that if the return value of the Memcache::add method is false, it means that the key already exists, while the Memcache::set method will overwrite it directly. The function of the Memcache::get method is to obtain a key value. The Memcache::get method has a parameter, which represents the key. The Memcache::replace method is used to overwrite an existing key. The Memcache::replace method has four parameters and has the same function as the Memcache::set method. The function of the Memcache::delete method is to delete a key value. The Memcache::delete method has two parameters. The first parameter represents the key , and the second parameter is optional and represents the deletion delay time. The Memcache::setServerParams method is used to modify the parameters of the server at runtime. The Memcache::setServerParams method has six parameters, and the Memcache::addServer method is missing the third and fourth parameters. The Memcache::getServerStatus method is used to obtain the parameters of the running server. The two parameters represent the address and port respectively. Memcache::increment method is used to add the value in a saved key, and the Memcache::decremen method is used to subtract the value in a saved key. Discuz!’s Memcache cache implementation Foreword:
The above has introduced the introduction and application of the debugging method in PHP using Memcache, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.
n";
n";
n";
/usr/local/memcached/bin/memcached: error while loading shared libraries: libevent-1.4.so.2:
cannot open shared object file: No such file or directory
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$version = $memc ache-> ;getVersion();
echo "Server's version: ".$version."n";
?>
01.02.$memcache = new Memcache;
03.$memcache->connect('localhost', 11211) or die ("Could not connect");
04.$memcache->set( 'name', 'leo', 0, 30);
05.if(!$memcache->add( 'name', 'susan', 0, 30))
06.{
07. echo 'susan is exist';
08.};
09.$memcache->replace( 'name', 'lion', 0, 300);
10.echo $memcache->get( 'name');
11.$memcache->delete( 'name', 5);
12.?>
01.02.function _callback_memcache_failure($host, $port) {
03. print "memcache '$host:$port' failed";
04.}
05.$memcache = new Memcache;
06.$memcache->addServer('192.168.1.116', 11211);
07.$memcache->setServerParams('192.168.1.116', 11211, 1, 15, true,
08.
09.'_callback_memcache_failure');
10.echo $memcache->getServerStatus('192.168.1.116', 11211);
11.?>
01.02.$memcache = new Memcache ;
03.$memcache->connect('localhost', 11211);
04.$memcache->set('test_item', 8);
05.$memcache->increment('test_item', 4 );
06.echo $memcache->decrement('test_item', 7);
07.// Display 5
08.?>
/usr/local/memcached/bin/memcached: error while loading shared libraries: libevent-1.4.so.2:
This BUG can be fixed
$memcache->connect('localhost', 11211) or die ("Could not connect");
$version = $memcache-> ;getVersion();
echo "Server's version: ".$version."
n";
?>
$memcache = new Memcache;
$memcache->connect('localhost', 11211 ) or die ("Could not connect");
print_r($memcache->getStats());
/**
* Array
* (
* [pid] => 8052
* [uptime] => 9205
* [time] => 1205898428
* [version] => 1.2.5
* [pointer_size] => 32
* [rusage_user] => 0.008000
* [rusage_system] => 0.000000
* [curr_items] => 1
* [total_items] => 17
* [bytes] => 57
* [curr_connections] => 2
* [total_connections] => 15
* [connection_structures] => 3
* [cmd_get] => 9
* [cmd_set] => 23
* [get_hits] => 5
* [get_misses] => 4
* [evictions] => 0
* [bytes_read] => 671
* [bytes_written] => 850
* [limit_maxbytes] => 10485760
* [threads] => 1
* )
*/
?>
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$memcache->set( 'name', 'leo', 0, 30);
if(!$memcache ->add( 'name', 'susan', 0, 30))
{
echo 'susan is exist';
};
$memcache->replace( 'name', 'lion', 0, 300 );
echo $memcache->get( 'name');
$memcache->delete( 'name', 5);
?>
function _callback_memcache_failure($host, $port) {T Print "MEMCACHE '$ Host: $ Port' Failed";
}
$ Memcache = New Memcache;
$ Memcache- & GT; addserver ('192.168.1.116'); $ memcache-& gt; setServerParams (' 192.168.1.116', 11211, 1, 15, true,
'_callback_memcache_failure');
ech o $memcache->getServerStatus('192.168.1.116', 11211);
?>
$memcache = new Memcache;
$memcache->connect('localhost', 11211);
$memcache->set('test_item', 8);
$memcache->increment('test_item', 4);
echo $memcache->decrement('test_item', 7);
// Display 5
?>
/tmp/memcached.pid
memcached’s service is officially started
Memcache::addServer — Add a server address for use
Memcache::close — Close a Memcache object
Memcache::connect — Create a Memcache object
memcache_debug — Control debugging Function
Memcache::decrement — Subtract the value in a saved key
Memcache::delete — Delete a key value
Memcache::flush — Clear all cached data
Memcache::get — Get a key value
Memcache::getExtendedStats — Get the running system statistics of all processes in the process pool
Memcache::getServerStatus — Get the parameters of the running server
Memcache::getStats — Return some running statistics of the server
Memcache::getVersion — Return the running Memcache version information
Memcache::increment — Add the value in a saved key
Memcache::pconnect — Create a Memcache persistent connection object
Memcache::replace — R overwrites an existing key Operation
Memcache::set — Add a value, if it already exists, overwrite it
Memcache::setCompressThreshold — Compress data larger than a certain size Memcache::setServerParams — Modify server parameters at runtime
Memcache::flush method is used to clear all cached data, but it will not reduce the used memory space.
In a PHP+MySQL architecture site, this article focuses on analyzing how to make the Discuz! Forum (or similar PHP+MySQL architecture program) cope with large visits from the perspective of MySQL. At the same time, some suggestions are given for using Memcache to reduce the pressure on MySQL. Many of the data are the results of personal testing. If you have different opinions, please leave a message. In addition, due to personal thinking problems, the writing is a bit jumpy, so I hereby declare it!
System analysis:
Purely from the perspective of MySQL, it should not be very difficult to load a single MySQL database to hundreds of millions of operations per day (about 1,100 MySQL operations per second, then multiplied by 86,400). According to this data, it is not a problem for a forum with a single MySQL server to reach 20 million PV. I believe that most domestic forums cannot achieve 20 million PV per day, but the actual situation is not Not so. When the PV of the forum exceeds one million, a WEB has already been overwhelmed.
Some data I have on hand shows that the current basic server architecture of Discuz! Forum is supported by Squid in the front and a DB in the back. In this architecture, the increased pressure on the web server can be solved by adding servers in parallel, but the pressure on MySQL has nowhere to release. Without considering the official MySQL service, we can reduce the load on the MySQL server by making reasonable use of Memcache. .
Some friends may say that we can sub-table the data table (note: sub-table here refers to sub-table through PHP program, such as pw, dv sub-table), but the current situation is that a DB server can no longer Although the current data processing is supported, splitting tables into MySQL through PHP still cannot reduce the load on MySQL. (Note: This paragraph is for an already formed system. If it is an independently developed system, it is good to synchronize data partitions in the early stage of the architecture.)
Some friends may also say to use the master-slave architecture of MySQL. If you propose this I will tell you the problem clearly, go back and read the manual. In the Mysql Master/Slave mode, the Slave is mainly used to back up data. Only when the Master fails, the Slave will take over the Master's service and process external requests until the Master returns to normal. That is to say: in Master/Slave, either Master is serving or Slave is serving, and Master/Slave will not provide services at the same time. Using MySQL master-slave still cannot effectively reduce the load of MySQL.
Perhaps you will ask me why I don’t use MySQL Cluster. It is a waste of money. With the same amount of money spent, the best way is to get the maximum benefit. PS: To make a digression, the MySQL manual explains MySQL cluster as MySQL cluster, which I am not used to.
In fact, the MySQL Partition in MySQL 5.1 is a very good thing. It allows multiple parts of a single table to be allocated across the file system according to rules that can be set to any size. In effect, different parts of the table are stored as separate tables in different locations. I think this is one of the most active and effective solutions to reduce MySQL load under the current situation. But unfortunately, I have no personal experience using this MySQL partitioning method, and there are no sufficient cases to show that it is stable or unstable. So I'm still wandering. If you know, please tell me! Some friends said that Tencent is using MySQL partitioning, but unfortunately I did not get the exact data.
After analyzing and summarizing so many ways to reduce the MySQL load, and under certain conditions such as user environment requirements, I came to the conclusion that under the current circumstances, the more effective way to alleviate the MySQL load of the Discuz! Forum is to use Memcache!
Reasons for using Memcache:
1. Web Server (Lighttpd and Nginx are said to be much more efficient than Apache, you can try them out) have high CPU requirements and low memory requirements; Memcached Server has low CPU requirements and low memory requirements High, so it can be used together. It is feasible to install Memcached Server on the front-end Web Server.
2. Money, money, money, the least effort, the greatest benefit.
3. Simple and simple. For a system with a reasonable architecture, adding Memcache support may be just a process of batch processing files
Discuz! Use Memcache
1. Add
$memcachehost = '127.0 in config.inc.php .0.1';
$memcacheport = 11211;
$memcachelife = 60;
2.In include/common.inc.php
$mem = new Memcache;
$mem->connect($memcachehost, $memcacheport);
3. Modify the fetch_array and query methods in include/db_mysql.class.php, and add the query_mysql method. The code is as follows:
function fetch_array($query, $result_type = MYSQL_ASSOC) {
return is_resource($query) ? mysql_fetch_array($query, $result_type) : $query[0];
}
function query_memcache($sql, $type = '') {
global $mem,$memcachelife;
$key = md5($sql);
if(!($query = $mem->get($key))) {
$query = $this->query($sql, $type);
while($item = $this->fetch_array ($query)) {
$res[] = $item;
}
$query = $res;
$mem->set($key, $query, 0, $memcachelife);
}
return $query ;
}
function query($sql, $type = '') {
global $debug, $discuz_starttime, $sqldebug, $sqlspenttimes;
$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?
'mysql_unbuffered_query' : 'mysql_query';
if(!($query = $func($sql, $this->link)) && $type != 'SILENT') {
$this->halt( 'MySQL Query Error', $sql);
}
if(substr($sql, 0, 6) == 'SELECT') {
echo 'Cache SQL:'.$sql.'
';
} else {
echo 'Flash SQL:'.$sql.'
';
}
$this->querynum++;
return $query;
}
4. The code for the SQL query that needs to be cached by Memcache is written by
$db- >query(
Modified to
$db->query_memcache(
Note and
while($post = $db->fetch_array($query)) {
Modified to
foreach($query as $post) {
$db->fetch_array without while does not need to be modified.
Take the following code if it is useful:
preg_replace("/while[Math Processing Error])/is", "foreach($query as $\1)", $file);
Release later Just replace the gadgets in batches.
You can replace it like this in EditPlus: while[Math Processing Error]) is replaced by foreach($query as $1)
5. It’s done, test it! ~
Reference materials:
Friends who have questions about Memcached can refer to the following articles:
Memcache installation under Linux: http://www.ccvita.com/index.php/257.html
Memcache installation under Windows: http: //www.ccvita.com/index.php/258.html
Memcache basic tutorial: http://www.ccvita.com/index.php/259.html
Discuz! Memcache cache implementation: http://www .ccvita.com/index.php/261.html