Detailed Redis tutorial, redis tutorial _ PHP Tutorial

Source: Internet
Author: User
Tags redis tutorial
Redis use detailed tutorial, redis tutorial. Redis detailed tutorial, redis tutorial 1, Redis basics: 1. redis introduction and installation are more than 10 times faster than mysql ******************** applicable to redis ******** * ******* 1. take the latest N data Redis detailed tutorial, redis tutorial

I. Redis basics:

1. redis introduction and installation are more than 10 times faster than mysql

****************

1. operations for retrieving the latest N data

2. ranking application, top n operations

3. applications that need to precisely set the Expiration Time

4. counter application

5. Uniq operation to obtain the values of all data records in a certain period of time

6. real-time system. The anti-spam system 7.Pub/ Sub constructs a real-time message system.

7. build a real-time message system using Pub/Sub 8. build a queue system

9. cache

========================================================== =====

The SET operation is performed 110000 times per second, and the GET operation is performed 81000 times per second. the server configuration is as follows:

Linux 2.6, Xeon X3320 2.5 Ghz.

The stackoverflow website uses Redis as the cache server.

Data is also written to the hard disk. Therefore, data is safe (except for sudden power outages, the restart service will be written to the dump. rdb file)

1. installation:

Tar zxvf redis-2.6.9.tar.gz

Cd redis-2.6.9

Make

Cd src & make install

2. move the configuration file location (for ease of management)

Cd/usr/local/

Mkdir-p/usr/local/redis/bin

Mkdir-p/usr/local/redis/etc

Mv/lamp/redis-2.6.9/redis. conf/usr/local/redis/etc

Cd/lamp/redis-2.6.9/src

Mv mkreleasehdr. sh redis-benchmark redis-check-aof redis-check-dump redis-cli redis-server/usr/local/redis/bin

3. modify the configuration file

Vi/usr/local/redis/etc/redis. conf

1. change no in daemonize no to yes [yes indicates running in the background]

4. start/random start:

Cd/usr/local/redis/bin

./Redis-server/usr/local/redis/etc/redis. conf # start redis and specify the configuration file.

# Vi/etc/rc. local # set random start.

/Usr/local/redis/bin/redis-server/usr/local/redis/etc/redis. conf

5. check whether the startup is successful.

Ps-ef | grep redis

Netstat-tunpl | grep 6379 # check whether the port is occupied.

6. enter the client/exit

Cd/usr/local/redis/bin

./Redis-cli # enter

Quit # exit

7. disable redis

Pkill redis-server # Disable

./Redis-cli shutdown # Disable

* ************************************ Redis security ** **********************************

Redis security ??? (In the following four ways)

1. use ACL controller for security.

2. add the following configuration in the redis. conf configuration file to bind redis to a single interface (but not only accept the data of this NIC ).

Bind 127.0.0.1

3. add a long password to redis (no need to remember)

4. enable authentication in redis. conf.

5. SSL proxy

6. disable the specified command.

* ************************************ Redis configuration **************************************** ******

To run daemonize in the background, change the value to yes.

The IP address of multiple PIDs configured in pidfile is/var/run/redis. pid by default.

Bind to an ip address. after setting, only requests from this ip address are accepted.

Port listening port. the default value is 6379.

Timeout sets the timeout time for client connection, in seconds

Loglevel is divided into four levels: debug, verbose, notice, warning

Logfile configuration log file address

Databases: sets the number of databases. the default value is 0.

Save sets the frequency of redis database mirroring

Whether to compress rdbcompression during image backup

Name of the backup file of the Dbfilename image

Directory of the Dir database image backup file

Slaveof sets the database as a slave database of another database

Password verification required for Masterauth primary database connection

Requirepass: Set the password used for logon.

Maxclients limits the number of customers connected at the same time

Maxmemory sets the maximum memory available for redis

Appendonly enabled append only mode

See the following:

Appendfsync sets the synchronization frequency for appendonly. aof files

Vm-enabled: whether to enable virtual memory support

Vm-swap-file: Set the swap file path of the virtual memory

Vm-max-memory: sets the maximum physical memory size used by redis.

Vm-page-size: sets the page size of the virtual memory.

Vm-pages: sets the total number of pages for file exchanges.

Vm-max-threads sets the number of threads simultaneously used by VM IO

Glueoutputbuf stores small output caches together

Hash-max-zipmap-entries sets the hash critical value

Activerehashing re-hash

**************************************** ***************************

Five data types: string, hash, linked list, set, and ordered set.

Supported: push/pop, add/remove, intersection, union, difference set, and sorting.

Redis <=== synchronization ==> mysql

Data is also written to the hard disk. Therefore, data is safe (except for sudden power outages, the restart service will be written to the dump. rdb file)

**************************************** ***************************

Select num # select the database. the default value is 0. There are 16 databases in total.

Auth liweijie # password required to authorize the user (the password is the password configured in redis. conf)

Flushdb # clear the database.

String type:

Set name lijie # set the key name to lijie

Get name # get the value of name.

Keys * # Query all keys.

Setnx name liweijie # if the key already exists, 0 is returned without updating to prevent overwriting.

Setex haircolor 10 red # set the key value to be valid for 10 seconds.

Setrange email 6 lampbre.com # replace the key value from 6th characters to lampbre.com

Mset name1 Li Dawei name2 Li Xiaowei # set the values of multiple keys.

Msetnxname1 Zhang San name3 Li Si # judge whether the key exists. if it does not exist, set it. otherwise, 0 is returned if it is not set.

Mget name1 name2 name3 # obtain the values of multiple keys at a time.

Getset name1 Tom # reset the key value and return the old key value.

Getrange email 6 18 # truncate the email key value, which is a string between 6 and 18 characters.

Incr uid # increase by 1 each time (if the uid in the key does not exist, set and start from 0, the same below)

Incrby uid 5 # Auto-Increment 5 each time

Incrby uid-5 # Auto-minus 5 each time

Decr uid # Auto-minus 1 each time

Decrby uid 5 # Auto-minus 5 each time

Appendname1 @ 126.com# add a string @ 126.com to the name1 value

Strlenname1 # Length of the value of the return key name1.

**************************************** *********************************

Hashes (hash) type:

Hset user: 001 name liweijie # hash setting the name key value of user: 001 is liweijie

Hset user: 001 age 21 # similarly, add an age key value of 21

Hsetnx user: 001 age 22 # Same as above, but check whether the key exists. If creation does not exist.

Hmset user: 002 name liweijie2 age 26 sex 1 # set the values of multiple keys at the same time.

Hget user: 001 name # hash to obtain the name key value of user: 001.

Hget user: 001 age # Same as above.

HMET user: 001 name age sex # obtain the values of multiple specified keys.

Hgetall user: 001 # obtain the values of all keys.

Hincrbyuser: 001 age-8 # add the given value to the specified key.

Hexists user: 001 sex # check whether the specified key value exists.

Hlen user: 001 # return the number of keys/fields in the specified hash.

Hdel user: 001 sex # Delete the specified field or key value of the specified (user: 001) hash.

Hkeys user: 003 # return all fields or key values in the hash.

**************************************** *****************************

Lists (linked list) type and operation (queue or queue ):

Lpush mylist "world" # insert a string from the header

Lpush mylist "hello" # Same as above

Lrange mylist 0-1 # obtain from 0 to the last one, for example, [1) "hello" 2) "world"]

Rpush mylist "jiejie" # insert at the end

Linsert mylist before "hello" "this is linsert" # specify the insert location (before hello ).

Lset mylist 0 "what" # set and modify the value of the specified subobject.

Lrem mylist 1 "hello" # Delete (1) an element with a value of hello. (N <0 is deleted from the end, n = 0 is all deleted)

Ltrim mylist 1 2 # Keep the element whose subscript is 1/2.

Lpop mylist # The start element is displayed and returned.

Rpop mylist # pop up the tail element and return it.

Rpoplpush mylist mylist2 # The header inserted to mylist2 is displayed at the end of mylist.

Lindex mylist 0 # obtain the element value whose subscript is 0.

Llen mylist # returns the number of table elements (equivalent to count ($ arr )).

**************************************** *****************************

Sets (set) types and operations (friend recommendation, blog, and tag functions ):

Smembers myset # View All element values in the myset set.

Sadd myset "hello" # Add a value hello to the mysets set

Srem myset "hello" # Delete an element named hello in the myset set.

Spop myset # randomly pops up and returns an element in mysets.

Sdiff myset2 myset3 # return the difference set between myset2 and myset3 (whichever is myset2 ).

Sdiffstore myset4 myset2 myset3 # return the difference set between myset2 and myset3, and store it in myset4.

Sinter myset2 myset3 # returns the intersection of myset2 and myset3.

Sinterstore myset5 myset2 myset3 # returns the intersection of myset2 and myset3 and stores it in myset5.

Sunion myset2 myset3 # Union (deduplication)

Sunionstore myset6 myset2 myset3 # calculates the union and stores it in myset6.

Smove myset2 myset3 "three" # Move three in myset2 to myset3.

Scard myset2 # returns the number of elements.

Sismember myset2 "one" # determine whether the element one is a set of myset2 (equivalent to is_array ()).

Srandmember myset2 # returns an element in the myset2 set at random, but does not delete it (equivalent to array_rand ()).

**************************************** *****************************

Sorted sets (sorted sets) types and operations (sorted by scores ):

Zadd myzset 1 "one" # Add one element to sequence 1

Zadd myzset 2 "two" # Same as above.

Zadd myzset 3 "two" # equivalent to the value in the update order of 2

Zrange myzset 0-1 withscores # View all elements and sort them in ascending order by default ).

Zrem myzset "two" # Delete two

Zincrby myzset 2 "two" # add the two sequence value to 2

Zrank myzset "two" # return the index value of the element in the set.

Zrevrank myzset two # The element is reversed and a new value is returned.

Zrevrange myzset 0-1 withscores # reverse in order (equivalent to descending order)

Zrangebyscore myzset 1 10 withscores # returns elements in the order of 1-10 (paging ).

Zcount myzset 1 10 # returns the number of elements in the order between 1 and 10.

Zcard myzset # returns the number of all elements in the set.

Zremrangebyrank myzset 1 2 # Delete the elements marked as 1 to 2 in the set.

Zremrangebyscore myzset 1 10 # delete elements from the set in the order of 1 to 10.

Common Redis commands

Key/value-related commands.

Keys * # Query all

Keys user * # query the specified

Exists user: 001 # determine whether the user exists.

Del name # Delete the specified key.

Expire addr 10 # set the Expiration Time

Ttl addr # query the Expiration Time

Select 0 # select database

Move age 1 # move age to database 1.

Get age # get

Persist age # the expiration time of the age to be removed.

Randomkey # returns a random key.

Rename name1 name2 # rename the key

Type myset # type of the return key.

Ping # test whether the redis connection is alive.

Echo lamp # output a lamp

Select 10 # select a database.

Quit/exit/crtl + C # exit the client

Dbsize # return the number of keys in the database.

Server commands:

Info # displays information about the redis server.

Config get */loglevel # returns all/specified configuration information.

Flushdb # Delete all keys/tables in the current database.

Flushall # Delete all keys/tables in all databases

II. Redis advanced section:

1. Redis security:

1. use ACL controller for security.

2. add a long password to redis

# Requirepass foobared

Requirepass beijing

3. enable authentication in redis. conf.

Method 1: Auth beijing

Method 2:./redis-cli-a beijing

4. add the following configuration in the redis. conf configuration file to bind redis to a single interface (but not only accept the data of this NIC ).

Bind 127.0.0.1)

5. SSL proxy

6. disable the specified command.

2. Redis master-slave replication:

Redis only needs to be configured on the slave server (slave:

Slaveof 211.122.11.11 6379 # specify the master's ip address and port

Masterauth beijing # This is the password of the master host

Info # view the status of the master/slave server.

3. Redis transaction processing:

Redis transactions are not perfect.

4. Redis Persistence mechanism:

1. two methods: 1. back up data to a disk (snapshot) [snapshotting (snapshot) is also the default method]

II. record the operation command [Append-only file (aof) method]

I. back up data to a disk (snapshot) [snapshotting (snapshot) is also the default mode]

Save 900 1 # if more than one key is modified within 900 seconds, the snapshot is saved.

Save 300 10 #300 seconds if more than 10 keys are modified, the snapshot is saved.

Save 60 10000

II. record the operation command [Append-only file (aof) method] (more secure and persistent)

Appendonly yes # enable aof persistence

# Appendfsync always // writes data to the disk immediately after receiving the write command, which is the slowest, but ensures full persistence.

Appendfsync everysec // writes data to the disk every second, which compromises performance and persistence.

# Appendfsync no // fully dependent on OS, which has the best performance and is not guaranteed for persistence

Redis basics: 1. redis introduction and installation are more than 10 times faster than mysql ******************** applicable to redis ******** * ******* 1. obtain the latest N data...

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.