This article brings the content is about PHP+REDIS+MYSQ how to handle high concurrency (instance code), there is a certain reference value, the need for friends can refer to, I hope to help you.
First, the experimental environment
Ubuntu, PHP, Apache or Nginx, MySQL
Second, demand
Now there may be a large number of concurrent interfaces, this interface is written by PHP, the function is to receive the user's Get Request Name field, and then save this field to MySQL, and now put the data in the Redis queue, Then let Redis periodically transfer this data to MySQL.
Ii. Steps of implementation
1. Create a new database test and data table test, the following table statement
CREATE TABLE ' test ' ( ' name ' varchar (255) default NULL) Engine=innodb default Charset=utf-8
1. Create a new index.php in/var/www/test with the following content and configure the virtual host to make it accessible.
<?php$redis = new Redis (), $redis->connect (' 127.0.0.1 ', 6379), try { $res = $redis->lpush (' name ', $_request ["name"]);} catch (Exception $e) { echo $e->getmessage ();}
2. In the same directory to create a new redis.php file, note that the database password changes in the configuration, such as the following
<?php$redis = new Redis (), $redis->pconnect (' 127.0.0.1 ', 6379); $mysql =mysqli_connect ("localhost", "root", "bnm" ); mysqli_select_db ($mysql, "test") or Die ("Cannot select Database"), if (! $mysql) {die ("Connection Failed");} while (true) { try{ $value = $redis->lpop (' name '); if (! $value) { echo "Wait"; } else{ $sql = "INSERT into test (name) VALUES ('". $value. "')"; $result =mysqli_query ($mysql, $sql); if ($result &&mysqli_affected_rows ($mysql) >0) { echo "Insert succeeded"; } else{ echo "Insert failed:". Mysqli_error ($mysql);}} catch (Exception $e) { echo $e->getmessage (); } Sleep (1);}
3. Run the redis.php script file
Nohup PHP redis.php &
4. Access the index.php script file, such as: http://192.168.116.128/?name=33, and see if the data is already in MySQL.
Related articles recommended:
What are the actions of the PHP array function? Application of PHP array functions (with code)
THINKPHP5 Framework and Android to implement the code of two-dimensional code generation