Redis Use detailed tutorials
First, the basic part of Redis:
1, Redis introduction and installation than MySQL faster than 10 times times
Applications for Redis ****************
1. Take the latest N data operation
2. Leaderboard application, top N operation
3. Applications that need to set the expiration time accurately
4. Counter Application
5.Uniq operation to get all data rows for a certain period of time
6. Real-time system, anti-spam System 7. Pub/sub Building a real-time messaging system
7.pub/sub Building a real-time messaging system 8. Building a queue system
9. Caching
=============================================
Set operations 110,000 times per second, get operations 81,000 times per second, the server is configured as follows:
Linux 2.6, Xeon X3320 2.5Ghz.
The StackOverflow website uses Redis as a cache server.
The data is also written to the hard disk. So the 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 profile location (for ease of administration)
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
First, the Daemonize No to Yes[yes refers to the background run]
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 #设置随机启动.
/usr/local/redis/bin/redis-server/usr/local/redis/etc/redis.conf
5. See if the startup is successful
Ps-ef | grep Redis
NETSTAT-TUNPL | grep 6379# to see if the port is occupied.
6. Enter the client/exit
Cd/usr/local/redis/bin
./redis-cli# Enter
quit# exit
7. Turn off Redis
Pkill redis-server# off
./REDIS-CLI shutdown# Close
Redis Security ************************************
Security??? for Redis (By the following 4 ways)
1. Use ACL controller security.
2. Add the following line configuration to the redis.conf configuration file to bind Redis to a single interface (but not only the data that accepts the NIC).
Bind 127.0.0.1
3. Add a longer password to Redis (no need to remember)
4. Enable the authentication feature in the redis.conf configuration.
5.SSL Proxy
6. Disable the specified command.
Redis Configuration **********************************************
Daemonize If you need to run in the background, change the item to Yes
Pidfile configure multiple PID addresses by default in/var/run/redis.pid
Bind bind IP, set only to accept requests from that IP
Port Listener, default = 6379
Timeout setting time-out for client connections in seconds
LogLevel is divided into 4 levels, debug, verbose, notice, warning
LogFile Configuring the log file address
Databases set the number of databases, the default database used is 0
Save sets how often Redis makes database mirroring
Rdbcompression whether to compress during a mirrored backup
Dbfilename file name for image backup
Dir file placement path for database mirroring backup
Slaveof setting the database to a different database from the database
Masterauth password verification required for primary database connection
Requirepass setting the password to use when logging in
MaxClients limit the number of simultaneous customers
MaxMemory set the maximum memory that Redis can use
AppendOnly Open Append Only mode
Here's what you can do:
Appendfsync Setting the frequency of synchronization for appendonly.aof files
Vm-enabled whether to turn on virtual memory support
Vm-swap-file setting the swap file path for virtual memory
Vm-max-memory Setting the maximum physical memory size used by Redis
Vm-page-size setting the page size for virtual memory
Vm-pages set the total page number of the interchange file
Vm-max-threads setting the number of simultaneous threads used by VM IO
GLUEOUTPUTBUF Store small output caches together
Hash-max-zipmap-entries setting the critical value of a hash
Activerehashing re-hash
*******************************************************************
5 Types of data: string, hash, linked list, collection, ordered collection.
Support: Push/pop, Add/remove, take intersection, set, difference set, sort.
redis<=== Synchronous ====>mysql
The data is also written to the hard disk. So the data is safe (except for sudden power outages, the restart service will be written to the Dump.rdb file)
*******************************************************************
Select num# Library, default in 0 libraries, total 16 libraries
Auth liweijie# the required password for authorized users (password is the password configured in redis.conf)
flushdb# clears the database.
String (String) type:
Set name lijie# The value of the key name is Lijie
Get name# Gets the value of name.
Keys * #查询所有的键.
Setnx name liweijie# returns 0 if the key already exists, and does not update to prevent overwriting.
Setex haircolor Red #设置键的值的有效期为10秒.
SetRange Email 6 lampbre.com# The value of the replacement key starts with the 6th character and changes to lampbre.com
Mset name1 li Dawei name2 Li Xiaowei # Sets the value of multiple keys.
Msetnxname1 Zhang San name3 John Doe # determines if the key exists, does not exist, or does not set to return 0
Mget name1 name2 name3# Gets the value of more than one key at a time.
Getset name1 tom# Re-sets the value of the key and returns the old key value.
GetRange Email 6 18# Intercept the value of the email key, from the 第6-18位 between the characters.
INCR uid# 1 per increment (if the UID in key does not exist, set and start at 0, same as below)
Incrby uid AA 5 per increment
Incrby uid-5# 5 per self-reduction
DECR UID #每次自减1
Decrby UID AA 5 per self-decrement
Appendname1 @126.com# to Name1 value, add string @126.com
strlenname1# returns the length of the value of the key name1.
*************************************************************************
Hashes (hash) type:
Hset user:001 name liweijie# Hash set user user:001 name key value is Liweijie
Hset user:001 Age 21# Also, add an age key value of 21
Hsetnx user:001 Age 22# Ibid, but the detection key is present. If no creation exists.
Hmset user:002 name Liweijie2 age of Sex # Sets the value of multiple keys at the same time.
Hget user:001 name# Hash Gets the value of the user user:001 name key.
Hget user:001 age #同上.
Hmget user:001 name Age sex# gets multiple values for the specified key.
Hgetall user:001# Gets the value of all keys.
hincrbyuser:001 age-8# adds the given value to the specified key.
Hexists user:001 sex# detects whether the specified key value exists.
Hlen user:001# Returns the number of keys/fields for the specified hash.
Hdel user:001 sex# Deletes the specified field or key value of the specified (user:001) hash.
Hkeys user:003# returns hash all fields or key values.
*********************************************************************
Lists (list) type and operation (in the case or queue):
Lpush mylist "World" #从头部插入字符串
Lpush mylist "Hello" #同上
Lrange mylist 0-1# gets from 0 to the last one such as [1] "Hello" 2) "World"
Rpush mylist "Jiejie" #在尾部插入
Linsert mylist before "Hello" "This is Linsert" #指定插入位置 (inserted before Hello).
LSet mylist 0 "what" #设置修改指定下标的值.
Lrem mylist 1 "Hello" #删除 (1) An element with a value of hello. (n<0 removed from tail, n=0 all removed)
LTrim mylist 1 2 #保留表中下标为1/2 elements.
Lpop mylist# pops up the opening element and returns.
Rpop mylist# pops up the trailing element and returns.
Rpoplpush mylist mylist2 #从mylist尾部弹出插入到mylist2的头部.
Lindex mylist 0# Gets the element value under the table labeled 0.
Llen mylist# Returns the number of table elements (equivalent to count ($arr)).
*********************************************************************
Sets (collection) type and operation (friend referral, blog, tag function):
Smembers myset# View all the element values in the MySet collection.
Sadd myset "Hello" #向mysets集合中添加一个值hello
Srem myset "Hello" #删除myset集合中名称为hello的元素.
Spop MySet #随机弹出并返回mysets中的一个元素.
Sdiff Myset2 myset3# Returns the difference from Myset3 in Myset2 (whichever is myset2).
Sdiffstore Myset4 Myset2 myset3# Returns the difference set in Myset2 with Myset3 and deposits 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 deposits it in Myset5.
Sunion Myset2 myset3# Seek and set (repeat)
Sunionstore Myset6 Myset2 myset3# Seek and set, and deposit into the MYSET6.
Smove Myset2 Myset3 "three" #将myset2中的three移到myset3中去.
SCard myset2# Returns the number of elements.
Sismember Myset2 "One" #判断元素one是不是myset2集合的 (equivalent to Is_array ()).
Srandmember myset2# randomly returns an element in the Myset2 collection, but does not delete (equivalent to Array_rand ()).
*********************************************************************
Sorted sets (ordered collection) types and operations (sorted in scores):
Zadd Myzset 1 "one" #向顺序1的添加元素one
Zadd myzset 2 "#同上".
Zadd Myzset 3 "#相当于更新顺序为2的值
Zrange Myzset 0-1 withscores# See all the elements and take the sort (by default ascending).
Zrem Myzset "The other" #删除two
Zincrby Myzset 2 "#将two的顺序值加上2
Zrank myzset "#返回集合中元素的索引下标值".
Zrevrank Myzset two# element reverses and returns the new subscript value.
Zrevrange myzset 0-1 withscores# in reverse order (equivalent to descending sort)
Zrangebyscore Myzset 1 withscores# Returns the element with the order 1-10 (can be paged).
Zcount Myzset 1 The number of elements between #返回顺序在1-10.
Zcard myzset# Returns the number of all elements in the collection.
Zremrangebyrank Myzset 1 * Delete the elements in the collection labeled 1 to 2.
Zremrangebyscore Myzset 1 10# deletes the elements in the collection that are sequentially 1 through 10.
Redis Common Commands
Key/value related commands.
Keys * #查询所有
Keys user* #查询指定的
exists user:001# to determine whether it exists.
Del name# deletes the specified key.
Expire addr 10# Set expiration time
TTL addr# Query Expiration Time
Select 0 #选择数据库
Move Age # Moves age to the 1 database.
Get Age #获取
Persist age# the expiration time of age is removed.
randomkey# randomly returns a key
Rename name1 name2# Rename key
Type myset# returns the kind of the key.
Ping #测试redis连接是否存活.
echo lamp# output a lamp
Select 10# Choose a database.
Quit/exit/crtl+c# exiting the Client
dbsize# returns the number of keys in the library.
Server-related commands:
info# displays information about the Redis server.
Config get */loglevel #返回所有/specified configuration information.
flushdb# Delete all keys/tables in the current library.
flushall# Delete all keys/tables in all databases
Second, the Redis Advanced section:
1. Redis Security:
1. Use ACL controller security.
2. Add a longer password to Redis
# Requirepass Foobared
Requirepass Beijing
3. Enable the authentication feature in the redis.conf configuration.
Way one: Auth Beijing
Way two:./redis-cli-a Beijing
4. Add the following line configuration to the redis.conf configuration file to bind Redis to a single interface (but not only the data that accepts the NIC).
Bind 127.0.0.1 (can be configured on a single machine, preferably not configured when distributed or master-slave replication)
5.SSL Proxy
6. Disable the specified command.
2. Redis Master-slave replication:
Redis can only be configured on the slave server (slave):
slaveof 211.122.11.11 6379 #指定master IP and port
Masterauth beijing# This is the master host's password
info# View the status of the primary/slave server.
3. Redis Transaction Processing:
Redis transactions are not perfect.
4. Redis Persistence mechanism:
1. Two ways: One, backup data to disk (snapshot) [Snapshotting (snapshot) is also the default mode]
Second, the record Operation command [Append-only file (abbreviated AOF) way]
One, backup data to disk (snapshot) [Snapshotting (snapshot) is also the default mode]
Save 1 #900秒内如果超过1个key被修改 to initiate a snapshot save
Save #300秒内容如超过10个key被修改, the snapshot save is initiated
Save 60 10000
Second, the record Operation command [Append-only file (abbreviated AOF) way] (more secure persistence)
AppendOnly Yes #启用aof persistence mode
# Appendfsync always//write commands are immediately written to disk, slowest, but guaranteed to be fully persisted
Appendfsync everysec//write disk once per second, a good compromise in performance and persistence
# Appendfsync no//completely dependent on OS, best performance, no guarantee of persistence
Redis Use detailed tutorials