Home >Backend Development >PHP Tutorial >Detailed tutorial on using Redis, redis tutorial_PHP tutorial

Detailed tutorial on using Redis, redis tutorial_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:50:22895browse

Detailed tutorial on using Redis, redis tutorial

1. Basic part of Redis:

1. The introduction and installation of redis is more than 10 times faster than mysql

**********************redis applicable occasions******************

1. Operation of getting the latest N data

2. Ranking application, take TOP N operation

3. Applications that require precise expiration time

4. Counter application

5. Uniq operation to obtain all data deduplication values ​​within a certain period of time

6. Real-time system, anti-spam system 7. Pub/Sub build real-time messaging system

7.Pub/Sub builds real-time messaging system 8. Builds queue system

9. Caching

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

SET operations are performed 110,000 times per second, and GET operations are performed 81,000 times per second. The server configuration is as follows:

Linux 2.6, Xeon X3320 2.5Ghz.

The stackoverflow website uses Redis as a cache server.

The data will also be written to the hard disk. So the data is safe (except for sudden power outages, restarting the 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 easier 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 configuration file

vi /usr/local/redis/etc/redis.conf

1. Change no in daemonize no to yes [yes refers to 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 startup.

/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 client/exit

cd /usr/local/redis/bin

./redis-cli#Enter

quit#quit

7. Close redis

pkill redis-server#Close

./redis-cli shutdown#Close

************************************Redis Security********* ***************************

The security of Redis???(by the following 4 ways)

1. Use ACL to control security.

2. Add the following line of configuration to the redis.conf configuration file to bind redis to a single interface (but it does not only accept data from this network card).

bind 127.0.0.1

3. Add a longer password to redis (no need to remember)

4. Enable the authentication function in redis.conf configuration.

5.SSL proxy

6. Disable specified commands.

**************************************** Redis Configuration ******* ***************************************

daemonize If you need to run in the background, change this item to yes

pidfile Configure the addresses of multiple pids. The default is /var/run/redis.pid

bind Bind IP, after setting, only accept requests from this IP

port listening port, default is 6379

timeout Set the timeout time when the client connects, in seconds

loglevel is divided into 4 levels, debug, verbose, notice, and warning

logfile Configure log file address

databases Set the number of databases. The default database is 0

save Set the frequency of database mirroring by redis

rdbcompression Whether to perform compression when performing image backup

Dbfilename The file name of the image backup file

Dir File placement path for database mirror backup

Slaveof Set the database as the slave database of other databases

Masterauth Password verification required for master database connection

Requirepass Set the password required when logging in

Maxclients limits the number of clients connected at the same time

Maxmemory sets the maximum memory that redis can use

Appendonly Turn on append only mode

You can learn about it below:

Appendfsync sets the frequency of synchronization of appendonly.aof files

vm-enabled Whether to enable virtual memory support

vm-swap-file sets the swap file path of virtual memory

vm-max-memory sets the maximum physical memory size used by redis

vm-page-size sets the page size of virtual memory

vm-pages sets the total number of pages in the swap file

vm-max-threads sets the number of threads used by VM IO at the same time

Glueoutputbuf stores small output buffers together

hash-max-zipmap-entries Set the critical value of hash

Activerehashing rehash

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

5 data types: string, hash, linked list, set, ordered set.

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

redis<===synchronization====>mysql

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

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

select num#Select library, default is 0 library, total 16 libraries

auth liweijie#The password required for authorized users (the password is the password configured in redis.conf)

flushdb#Clear the database.

String (string) type:

set name lijie#Set the value of key name to lijie

get name#Get the value of name.

keys *#Query all keys.

setnx name liweijie#If the key already exists, it returns 0 and does not update to prevent overwriting.

setex haircolor 10 red #The value of the set key is valid for 10 seconds.

setrange email 6 lampbre.com#The value of the replacement key is changed to lampbre.com starting from the 6th character

mset name1 Li Dawei name2 Li Xiaowei #Set the values ​​of multiple keys.

msetnxname1 Zhang San name3 Li Si# Determine whether the key exists, set it if it does not exist, otherwise return 0 if not set

mget name1 name2 name3#Get the values ​​of multiple keys at one time.

getset name1 Tom#Reset the key value and return the old key value.

getrange email 6 18#Intercept the value of the email key, starting from the characters between 6th and 18th.

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

incrby uid 5# increases by 5 each time

incrby uid -5# Decrease by 5 each time

decr uid #Decrease by 1 each time

decrby uid 5# decreases by 5 each time

appendname1 @126.com#Add the string @126.com to the value of name1

strlenname1#Returns the length of the value of key name1.

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

Hashes (Hash) type:

hset user:001 name liweijie#Hash sets the name key value of user user:001 to 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. Create if it 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 gets the value of the name key of user user:001.

hget user:001 age #Same as above.

hmget user:001 name age sex#Get the values ​​of multiple specified keys.

hgetall user:001#Get 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#Returns the number of keys/fields of 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 (stack or queue):

lpush mylist "world"#Insert string from the head

lpush mylist "hello"#Same as above

lrange mylist 0 -1#Get from 0 to the last one such as [1) "hello" 2) "world"]

rpush mylist "jiejie"#insert at the end

linsert mylist before "hello" "this is linsert" #Specify the insertion position (insert before hello).

lset mylist 0 "what"#Set and modify the value of the specified subscript.

lrem mylist 1 "hello"#Delete (1) an element with the value hello. (n<0 is deleted from the tail, n=0 is deleted entirely)

ltrim mylist 1 2 #Reserve the elements with subscript 1/2 in the table.

lpop mylist# Pop the beginning element and return.

rpop mylist# Pop the tail element and return.

rpoplpush mylist mylist2 #Pop from the end of mylist and insert it into the head of mylist2.

lindex mylist 0#Get the element value with table subscript 0.

llen mylist#Returns the number of table elements (equivalent to count($arr )).

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

sets type and operation (friend recommendation, blog, tag function):

smembers myset#View all element values ​​in the myset collection.

sadd myset "hello"#Add a value hello to the mysets collection

srem myset "hello"#Delete the element named hello in the myset collection.

spop myset #Randomly pop up and return an element in mysets.

sdiff myset2 myset3#Returns the difference between myset2 and myset3 (subject to myset2).

sdiffstore myset4 myset2 myset3#Return the difference between myset2 and myset3, and store it in myset4.

sinter myset2 myset3#Returns the intersection of myset2 and myset3.

sinterstore myset5 myset2 myset3#Return the intersection of myset2 and myset3 and store it in myset5.

sunion myset2 myset3# Find the union (remove duplicates)

sunionstore myset6 myset2 myset3# Find the union and store 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 in the myset2 set (equivalent to is_array()).

srandmember myset2# Randomly returns an element in the myset2 collection, but does not delete it (equivalent to array_rand()).

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

sorted sets (ordered set) type and operation (sorted by scores):

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

zadd myzset 2 "two"# Same as above.

zadd myzset 3 "two"# Equivalent to the value whose update order is 2

zrange myzset 0 -1 withscores#View all elements and sort them (default ascending order).

zrem myzset "two"#Delete two

zincrby myzset 2 "two"#Add 2 to the sequence value of two

zrank myzset "two"#Returns the index subscript value of the element in the set.

zrevrank myzset two#Reverse the element and return the new subscript value.

zrevrange myzset 0 -1 withscores#Reverse in order (equivalent to sorting in descending order)

zrangebyscore myzset 1 10 withscores#Return elements in order 1-10 (can be paginated).

zcount myzset 1 10 #Return the number of elements in the order between 1-10.

zcard myzset#Returns the number of all elements in the set.

zremrangebyrank myzset 1 2#Delete elements with subscripts 1 to 2 in the set.

zremrangebyscore myzset 1 10#Delete elements from 1 to 10 in the set.

Redis common commands

Key/value related commands.

keys * #Query all

keys user*#Query the specified

exists user:001#Determine whether it exists.

del name#Delete the specified key.

expire addr 10#Set expiration time

ttl addr#Query expiration time

select 0 #Select database

move age 1#Move age to database 1.

get age #Get

persist age#Remove the expiration time of age.

randomkey#Returns a key randomly

rename name1 name2#Rename key

type myset#Return the type of key.

ping #Test whether the redis connection is alive.

echo lamp#Output a lamp

select 10#Select database.

quit/exit/crtl C# exit the client

dbsize#Returns the number of keys in the library.

Server related commands:

info#Displays information about the redis server.

config get */loglevel #Return all/specified configuration information.

flushdb#Delete all keys/tables in the current library.

flushall#Delete all keys/tables in all databases

2. Redis advanced part:

1. Redis security:

1. Use ACL to control security.

2. Add a longer password to redis

#requirepass foobared

requirepass beijing

3. Enable the authentication function in redis.conf configuration.

Method 1: Auth beijing

Method 2: ./redis-cli -a beijing

4. Add the following line of configuration to the redis.conf configuration file to bind redis to a single interface (but it does not only accept data from this network card).

bind 127.0.0.1 (can be configured on a single machine, but it is best not to configure it on distributed or master-slave replication)

5.SSL proxy

6. Disable specified commands.

2. Redis master-slave replication:

redis only needs to be configured on the slave server:

slaveof 211.122.11.11 6379 #Specify the master’s ip 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 very imperfect.

4. Redis persistence mechanism:

1. Two methods: 1. Back up data to disk (snapshot) [snapshotting (snapshot) is also the default method]

2. Record operation commands [Append-only file (abbreviation aof) method]

1. Back up data to disk (snapshot) [snapshotting (snapshot) is also the default method]

save 900 1 #If more than 1 key is modified within 900 seconds, initiate a snapshot save

save 300 10 #If more than 10 keys are modified within 300 seconds, a snapshot will be saved

save 60 10000

2. Record operation commands [Append-only file (abbreviated as aof) method] (safer and more durable)

appendonly yes #Enable aof persistence method

# appendfsync always //Write to the disk immediately after receiving the write command, the slowest, but ensuring complete persistence

appendfsync everysec //Write to disk once per second, making a good compromise between performance and persistence

# appendfsync no //Completely dependent on os, best performance, no guarantee of persistence

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1133575.htmlTechArticleRedis usage detailed tutorial, redis tutorial 1, Redis basics: 1. The introduction and installation of redis is 10 times faster than mysql The above******************redis applicable occasions****************** 1. Get the latest N data...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn