PHP database operation 3: redis Usage Analysis, php database redis usage

Source: Internet
Author: User
Tags php database install redis

PHP database operation 3: redis Usage Analysis, php database redis usage

This article describes how to operate redis in a PHP database. We will share this with you for your reference. The details are as follows:

Although memcache is easy to use, it solves the IO problem when the database encounters high concurrency, but there are still many issues to be resolved:

1. Data Persistence: memcache is stored in memory. Once the memcache server goes down, all the stored data is lost.

2. memcache stores a single data type and only supports key-value data. To store complex types of data, a large number of logical operations of PHP scripts are required.

Redis Basic Introduction

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

With the added data persistence feature, redis uses the rdb and aof methods to achieve data persistence. When the server suddenly goes down, it can retain almost all the data that has been stored.
Added string, set, sorted_set, hash, and list data types to facilitate multiple types of storage and database operations.
Added security verification (you can set a connection password for the server ).
Apsaradb for redis has better master-slave separation systems (officially developed ).
Native supports tools such as publishing/subscription, queue, and cache.

Of course, compared with memcache, its database operations are also complicated.

Application scenarios and installation of redis

Redis can be used in addition to memcache:

You can use a linked list to store data and read its latest information.
You can use an ordered list to store data and read its ranking data.
You can use a collection to store the followed/followed information.

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

After the installation is complete, mv the redis conf file in the installation package to the bin directory of the installation directory, which is required to configure and start redis.

In addition, the bin directory under the installation directory file contains the following files.

Redis-benchmark // Performance Testing Tool-n xxx indicates that xxx commands are issued for testing
Redis-check-aof // a tool for checking aof logs
Redis-check-dump // tool for checking rbd logs
Redis-cli // Client
Redis-server // redis server process
Redis-sentinel // redis sentinel mode process

We use vim to open redis. conf to easily configure the redis server.

Change the daemonize option to yes to run in the background.
Database n sets a redis server to have n servers. The default value is 0-15, a total of 16 servers.
Port n to set the listening port of the redis Server
Set requirepass yourpassword to set the password. After the client connects, use auth password for verification.

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

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

Redis commands

Basic (including string type) commands

Set key value [ex | px n] // set the value [and set the expiration time to n seconds/millisecond] get key // get the value del key // Delete the value incby | decby key n // auto-increment or auto-Subtract nrename key newkey // overwrite the original select n // select the ttl key of the nth database // query the expiration time of the key, -1 indicates that it never expires, -2 expire key n does not exist // set the key expiration time to n seconds type key // get the key storage type flushdb // clear the value of the current database shutdown [nosave]/ /disable the server [not stored]

List (linked list) command

Lpush/rpush list value1 [value2 value3. ..] // press value into the chain table Header/tail lpop/rpop list // The value of the chain table Header/tail llen list // obtain the length of the chain table

Set command

Sadd set value // Add valuesmembers set to the set // view all data in the set srem set value1 [value2...] // Delete the element sismember set value in the set // determine whether the value is an element in the set

Sorted_set (ordered set) command

Zadd sorted_set score1 key1 score2 key2 score3 key3. Add a key to the sorted set and define its score. The set uses the score to sort the key.
Zrange sorted_set a B [withscores] display all when the value B in the order list is-1 from a to B, [display score of each value]
Zrank/zrevrank sorted_set key positive/reverse display the position of the key in the Ordered Set
Zrem sorted_set key: Delete the key in the sorted set
Zcard sorted_set [m n] calculates the total number of [scores between m and n] in an ordered set.

Hash (hash type) command

Hset hashset key value: set the value of the hash table key to value.
Hget hashset key obtains the key value of the hash table.
Hdel hashset key: delete a key in the hash table
Hlen hashset obtains the length of the hash table.

There are many redis commands. Here we only list a few simple commands. The specific commands can be translated on the official website or on its Chinese site http://www.redis.cn /#

Redis transactions and publishing and subscription

Transactions in redis are similar to those in mysql. Only statements are different.

Redis mysql starts the transaction query statement in the multi start transition transaction to execute the transaction exec commit rollback transaction discard roll back

For the impact of concurrency, redis has the watch statement control. Once the key value monitored by the watch statement changes before the transaction is committed, the transaction is automatically canceled and rolled back.

Watch key1 [key2. ..]
Unwatch cancels all monitoring.

The native publish and subscribe function of redis is similar to the observer mode in the design mode. Once a subscribed object publishes a new message, all subscribed objects will receive this message. Usage:

Subscribe key // subscribe to a key. If a new message is published, the public key value // publishes the Message key with the value of value, the returned value is the number of recipients of the message. unsubscribe key // cancel listening for psubscribe key1 key2/pattrn // [mode-based] Listen for multiple keys

Redis data persistence

Redis achieves data persistence through rdb and aof, both of which occupy CPU resources and slow down the execution efficiency of redis.

The main principle of the rdb method is to save a snapshot of all data in the memory to the disk after a certain write condition is reached, and recover the data with a data snapshot.

The aof method is to record each redis command into a text file, and repeat the command to restore data.

Data persistence through rdb

The save/bgSave command can be used to store rdb in the [background] mode.

Modify the redis. conf file for configuration

Save m n // if there are n modifications within m seconds, a snapshot is taken. The storage point is very important. Generally, multiple conditions are configured, if either of them is met, save stop-writes-on-bgsave-error yes // if an error occurs during the snapshot process, then stop writing data into rdbcompression yes // set for Data Compression rdbchecksum yes // when importing data, check whether the file is damaged dbfilename xxx. rdb // export file name dir path // export file path

Aof Method for Data Persistence

The problem with aof persistence is that every instruction is recorded. Even repeated operations on a key may cause the aof file to become larger and larger, using aof rewrite will greatly reduce the size of the aof file, because it is at last converting the state of data in the database into a command, regardless of how many times a key has changed. You can use the bgrewrite command to manually override the aof file.

Configure the redis. conf file:

Noapppendfsync-on-rewrite yes // when exporting rdb, stop writing aof. aof will be written in the memory queue. After dump rdb is complete, write operations will be performed in a unified manner. Appendfsync everysec // write appendfilename once per second // path/filename. aofauto-aof-rewrite-percentage 100 // when the file size increases by 100%, rewrite auto-aof-rewrite-min-size 64 m // when the file size reaches 64 m at least

Master-slave replication of redis

During master-slave replication, the master-slave instance must start the server with its own. conf file. The master server can shut down rdb to generate rdb from the server, accelerating the speed of the master server.

Copy A redis6380.conf file from the server, set the port, pid to store the file, read-only, and master server password.

port 6380pidfile filenameslave-read-only yesmasterauth password

After the configuration is complete, use different conf files to open the server.

Considering that the master server is down, we use sentinel redis to monitor the server status and respond after the master server is down. Sentinel is integrated with redis. We only need to copy the sentinel. conf file in the installation package to the redis/bin directory and use the redis-sentinel process file to start the server.

Port 26379 // The port number daemonize listened by sentinel yes // The background Startup Process sentinel monitor mymaster 192.168.100.211 6379 2 // set the master process ip address and port number, and set the two sentinel to identify that the master server is down after a long time cannot be connected. sentinel down-after-milliseconds mymaster 30000 // 30000 milliseconds cannot be connected. It is determined that sentinel parallel-syncs mymaster 1 cannot be connected. // when a master server is enabled, at the same time, the number of slave servers to be copied is too large, which will cause instant server congestion. sentinel failover-timeout mymaster 900000 // within 90000 seconds, the sentinel no longer tries to restore the original master server

PHP operations on redis Server

After installing the redis extension of php (For details, refer to the previous article Linux php install Redis Extension Method http://www.bkjia.com/article/99775.htm), you can directly use the redis class function library.

The following are typical redis applications.

$ Redis = new Redis (); // instantiate a Redis object $ redis-> connect ('host', port ); // connect to the redis server $ redis-> auth ('Password'); // use a password to authenticate $ redis-> set ($ key, $ value [, $ expire_time]); // set a value $ content = $ redis-> get ($ key); // obtain the value

Specific function use can see the official documentation: https://github.com/phpredis/phpredis

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.