Usage and analysis of PHP database Redis

Source: Internet
Author: User
Tags php database redis server
This article mainly introduces the PHP database operation Redis Usage, combined with the example form detailed analysis of PHP installation, the use of Redis procedures, methods and related considerations, the need for friends can refer to the following

Specific as follows:

Memcache Although easy to use, solve the database encountered high concurrency when the IO problem, but there are many problems to solve:

1, data persistence problem, memcache memory storage, once the Memcache server down, then all the data stored is lost.

2, memcache storage data type is single, support only key-value type of data, to store complex types of data, it is necessary to PHP script a lot of logical operation.

Basic Introduction to Redis

Redis is also a memory non-relational database, it has all the advantages of memcache on the data storage, and on the basis of Memcache (Memcache introduction can be seen in the previous article: http://www.jb51.net/article/121315.htm

With the addition of data persistence capabilities, Redis uses an RDB and aof to achieve data persistence in two ways, and it retains almost all of its existing data when the server is suddenly down.
The addition of string (string), set (set), Sorted_set (ordered collection), hash (hash), list (linked list) data types facilitates multiple types of storage and database operations.
Added security verification (you can set the connection password for the server).
Redis's master-slave separation system is more complete (official development).
Native support for publish/subscribe, queue, cache and other tools.

Of course, compared with memcache, its database operation is also more complex.

Application scenarios and installation of Redis

In addition to being used in Memcache, Redis can also be used in:

You can use a linked list to store data and read its latest information.
You can store data in an ordered list and read its leaderboard data
You can use collections to store attention/attention messages.

Download to its latest version on the official website (http://redis.io/), unzip it directly, because the REDIS official has been compiled, directly to the Make/make test, you can specify its installation path when make install.

After the installation is complete, the Redis conf file in the package will be installed in MV to the bin directory of the installation directory, which is required to configure and start Redis.

In addition to this, the following files are available in the Bin directory under the installation directory file.

Redis-benchmark//performance test tool-n XXX means to issue the XXX bar to test
REDIS-CHECK-AOF//tools for checking aof logs
Redis-check-dump//tools for checking RBD logs
REDIS-CLI//Client
Redis-server//redis Server process
Redis-sentinel the process of//redis Sentinel mode

We use VIM to open the redis.conf to simply configure the Redis server.

Change the daemonize option to Yes to run in the background
Database n set up a Redis server has n servers, the default is 0-15 a total of 16
Port N to set the listening port for the Redis server
Set Requirepass YourPassword to set the password, after the client connects with auth password to pass the authentication

We use the./redis-server./redis.conf command to open the Redis server.

Use./redis-cli [-P port] to connect to the server (default 6379).

The Redis command

Basic (including string string type) commands

Set key value [EX|PX N]//Set value [and set expiration time to n seconds/msec]get key//Get Value del key//delete value Incby|decby key N//Add key value self-increment or decrement nrename key newkey//overwrite The original select n//selects the nth database TTL key//query key expiration time, 1 means never expires, does not exist for -2expire key n//Set key expiration time is n seconds type key//Get key Storage type FLUSHDB// Clears the value in the current database shutdown [nosave]//shutdown server [does not store]

List (linked list) command

Lpush/rpush list value1 [value2 value3 ...]//pressing value into the chain header/tail Lpop/rpop list//Popup list Header/tail values Llen list/get linked list length

Set (Collection) command

Sadd Set value//Add Valuesmembers set//View all data in collection Srem set Value1[value2 ...] Delete an element from a collection Sismember set value//Determine if value is an element in the collection

Sorted_set (ordered Collection) command

Zadd sorted_set score1 key1 score2 key2 score3 Key3 ... Adds a key to an ordered collection and defines its score, which the collection sorts with score
Zrange Sorted_set a B [withscores] displays all when the value B in the sequence table is 1 from a to B, [shows the score of each value]
Zrank/zrevrank Sorted_set Key positive/reverse shows the position of key in an ordered set
Zrem sorted_set key removes key from an ordered collection
Zcard Sorted_set [M n] Calculates the total number of [score between M and N] in an ordered set

Hash (hash type) command

Hset HashSet key value sets the hash table key to
Hget hashset key Gets the key value of the hash table
Hdel hashset key removes a key from the hash table
Hlen HashSet Get the length of the hash table

Redis commands are numerous, here are only a few simple, specific commands can be its official website or its Chinese station http://www.redis.cn/view translation documents

Redis transactions and publications, subscriptions

Transactions in Redis are similar to MySQL, and only statements are somewhat different.

        Redis        MySQL starts transaction    multi start      transition          The query statement in the transaction executes the transaction    EXEC        commit rollback TRANSACTION    Discard       Roll back

For concurrency effects, Redis has watch statement control, and the transaction is automatically canceled when the key value monitored by the Watch statement changes before the transaction commits.

Watch Key1 [Key2 ...]
Unwatch Cancel all monitoring.

The Redis native Publishing and subscription feature, which resembles the observer pattern in design mode, receives this message for all subscription objects once a new message is published by the subscribed object. How to use:

Subscribe key//Subscribe to a key, if this key has released a new message, you will receive the public key value//post message key, value is the number of the person who received the message unsubscribe key// Psubscribe key1 KEY2/PATTRN//[monitor multiple keys based on mode)


Data persistence for Redis

Redis achieves data persistence in two ways with Rdb and aof, both of which consume CPU resources and slow down the execution efficiency of redis, typically in combination with two modes.

The main principle of the RDB approach is to save a snapshot of all the data in memory to disk when a certain write condition is reached, and restore the data with a snapshot of the data when it is recovered.

The AoF method is to repeat the logged command when recovering data by logging each Redis execution command into a text file.

RDB for data persistence

Use the Save/bgsave command to proactively store an RDB in an RDB way [backend]

Modify the redis.conf file for configuration

Save m n          //In M seconds there are n changes to take a snapshot, save point is very important, usually configure multiple conditions, to meet one of the save Stop-writes-on-bgsave-error Yes//in the process of taking a snapshot if an error occurs, Stop writing Rdbcompression Yes     //settings for data compression rdbchecksum Yes/       /check file corruption when importing data dbfilename Xxx.rdb     //export filename dir path          //Exported file path

AoF way to achieve data persistence

The problem with aof persistence is that each instruction is recorded, even if it is repeated on a key, which causes the aof file to become larger, and using AOF overrides will greatly reduce the volume of the AoF file, since it is the last to unify the state of the data in the database into the command, Regardless of how many times a key has changed. Use the Bgrewrite command to manually override the AoF file.

To configure the redis.conf file:

Noapppendfsync-on-rewrite Yes    //set to stop writing when exporting an RDB aof,aof is written in the memory queue, and the dump RDB is completed uniformly for write operations. Appendfsync everysec        //write once per second appendfilename           //path/filename.aofauto-aof-rewrite-percentage   // Rewrite auto-aof-rewrite-min-size 64m    //file at least 64m when file size is increased by 100%

Redis Master-slave replication

Master-slave replication, the master and slave should start the server with their own. conf file. The master server can turn off the RDB to generate an RDB from the server, speeding up the primary server.

Copy a redis6380.conf file from the server, set the port, PID to store the file, read-only, and the password of the master server.

Port 6380pidfile filenameslave-read-only yesmasterauth Password

Once setup is complete, open the server with a different conf file, respectively.

With the primary server down, we use Sentinel Redis Sentinel to monitor the status of the server and respond after the primary server goes down. Sentinel is a Redis integration, we only need to copy the sentinel.conf files in the installation package to the Redis/bin directory, using the Redis-sentinel process file to start the server.

Port 26379                    //sentinel Monitor port number daemonize Yes                  //Background boot Process Sentinel monitor MyMaster 192.168.100.211 6379 2// Set the main process IP and port number, and set two sentinels to find that the primary server was unable to connect for a long time to determine its downtime Sentinel down-after-milliseconds MyMaster 30000//30000 milliseconds connection not determined to be unable to connect Sentinel Parallel-syncs MyMaster 1        //When a primary server is turned on, the number of simultaneous copies from the server, too large will cause the server to instantly congestion Sentinel Failover-timeout MyMaster 900000    // Sentinel no longer attempts to restore the primary server within 90,000 seconds

PHP Operation Redis Server

After installing the Redis extension for PHP (refer to the previous article Linux installation of the Redis extension method http://www.jb51.net/article/99775.htm), you can directly use the Redis class function library.

The following is a typical Redis application.

$redis =new Redis ();           Instantiate a Redis object $redis->connect (' host ', port);      Connect Redis server $redis->auth (' password ');        Password Authentication $redis->set ($key, $value [, $expire _time]);//Set a value $content= $redis->get ($key);       Get value

Related Article

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.