Redis is also a key-value storage system, the official site Http://redis.io, but with respect to memcache, there are the following advantages:
1. Support More value types (string, hash, lists, sets, sorted sets, etc.);
2, support data persistence, prevention service restart need to re-storage;
Redis has two file formats: full-volume data (Rdb=redis database), incremental request (Aof=append only file).
The former is to write in-memory data into the disk, so that the next time to read the file directly loaded, snapshot form;
The latter is a record of the instructions performed by Redis, which is performed again when restarted, similar to binlog storage;
Two ways can be used at the same time, restart at this time, will first use aof to restore;
Either way, Redis becomes a memory database, like memcache;
Redis Storage: Memory storage, disk storage, log files three parts
Installation
First wget Download the source package, Https://code.google.com/archive/p/redis/downloads
Example: wget https://codeload.github.com/antirez/redis/tar.gz/2.8.21
Unzip: Tar zxvf 2.8.21 && CD redis-2.8.21
Yum install-y gcc epel-release; Yum install-y jemalloc-devel//make before installing some tools
Compile: Make//Because Makefile is already written, no need to compile, just make it.
650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M01/8A/80/wKioL1gyuxvzyDYmAACEQbcOx7I493.png-wh_500x0-wm_3 -wmp_4-s_3223243082.png "title=" 1.png "alt=" Wkiol1gyuxvzydymaaceqbcox7i493.png-wh_50 "/>
Error: If make is wrong, you are not prompted to find something #我用的centos7, but there is no error
FIX: cd deps && make Hiredis lua jemalloc linenoise && CD. /&& Make
Installation: Make Prefix=/usr/local/redis Install//for easy management, specify the following directory
Created: Mkdir/usr/local/redis/etc &&/usr/local/redis/var
wget Http://www.apelearn.com/study_v2/.redis_init-O/etc/init.d/redis//Teacher's startup script
Users: Useradd-s/sbin/nologin Redis
Permissions: chmod 777/usr/local/redis/var && chmod 755/etc/init.d/redis
Self-starter: chkconfig--add redis && chkconfig redis on && service Redis start
Data type
String: Can be understood as memcache type, a key corresponding to a value, function than mem rich, the simplest type;
Set: Set, common in the collection of orthogonal difference, such as micro-blog common concern, common fans, QQ friends tags and other functions;
Lists: Chain list structure, function push, pop, access range, etc., easily achieve the functions such as ranking;
Hash: Hashing, MEM packaging structured information into HashMap, serialized and stored in a character, such as age and gender;
Sorted set: Ordered set, more than set weight parameter score, so that it can be arranged according to score, insert also have order;
Configuration file
# # #通用配置daemonize no #默认情况下, Redis is not run in daemon form. pidfile /path/to/redis.pid #当以daemon形式运行时, pointing to the generated PID file bind 192.168.1.2 10.8.4.2 #指定绑定的ip, can have multiple, space-delimited port 6379 #指定监听端口unixsocket /tmp/redis.sock #也可以监听socketunixsocketperm 755 # You can specify a permission of 755timeout 0 when listening to a socket #客户端时间内没向服务端发请求, the server closes the connection by this value, 0 means never shut down tcp-keepalive 0 #TCP连接保活策略, detect the client is not hung off, 0 means do not open loglevel notice #日志级别, there are four kinds of debug, verbose, notice, warninglogfile "" #定义日志路径, "" means default syslog-ident redis #通过syslog-enabled to control Print to Syslog, this value specifies the log flag in the Syslog syslog-facility local0 #指定syslog的设备, can be user or local0-local7databases 16 #设置数据库的总数量 # # #快照配置save 900 1 #表示每15分钟且至少有1个key改变, Triggers a one-time persistence save 300 10 #表示每5分钟且至少有10个key改变, trigger a persistent save 60 10000 # Indicates that there are at least 10,000 key changes every 60 seconds to trigger a persistent save "" &nbSP; #这样可以禁用rdb持久化stop-writes-on-bgsave-error yes #写入磁盘失败后, stop the write operation immediately rdbcompression yes #是否要压缩rdbchecksum yes #是否进行数据校验dbfilename dump.rdb #定义快照文件的名字dir /usr/local/redis #定义快照文件储存路劲 # # #安全相关配置requirepass teng #设置redis-server password # #测试:redis-cli & & get key1 :redis-cli -a teng && get after restart key1 will be different. Output rename-command config teng.config ## Renaming the config command to Teng.config avoids misoperation, but if aof persistence is used, it is not recommended to enable the feature rename-command config "" #也可以后面定义为空 so that the config is bannedCommand # # #限制相关配置maxclients 10000 # Limit the maximum number of client connections maxmemory <bytes> # Sets the maximum number of memory usage in bytemaxmemory-policy volatile-lru #指定内存移除规则maxmemory-samples 3 #LRU和TTL算法都是估算值. So you can set the size of the sample. #快照key触发, then you can change the number of this key sample. # # #AOF持久化appendonly no # If no, turn on aof persistence appendfilename "apponly.aof" #指定aof文件名字appendfsync everysec #三种模式, fastest no (do not call fsync), safest always (Every write will #调用fsync), the default everysec (Fsync is called once per second). no-appendfsync-on-rewrite no # Set Yes, Avoids disk IO blocking when the write volume is very large auto-aof-rewrite-percentage 10 #10 = = When the aof file increases by up to 10% Will trigger the override mechanism uto-aof-rewrite-min-size 64mb #重写会有一个条件, which is not less than 64mb### Slow log correlation slowlog-log-slower-than 10000 # Log slowlog-max-len 128 #日志长度 slower than 10000ms, Delete oldest log when greater than 128
# # # line Example # # # # # #daemonize yespidfile/usr/local/redis/var/redis.pidport 6379timeout 300loglevel debuglogfile/usr/local/ Redis/var/redis.logdatabases 16save 1save 10save 10000rdbcompression yesdbfilename dump.rdbdir/usr/local/ Redis/var/appendonly Noappendfsync always
Master-Slave synchronization
Master Master |
192.168.1.1 |
from slave |
192.168.1.2 |
Install Redis as described above and start, master profile does not move, slave configuration file plus downlink:
Slaveof 192.168.1.1 6379//Primary IP and port
Masterauth passwd//If the Lord sets a password, add this line
To restart the test:
Master >> redis-cli set key0 1 && redis-cli get key0 = = Output 1
Slave >> redis-cli Get key0 = = Output 1
slave-read-only yes # lets you set slave from read-only repl-ping-slave-period 10 # to ping to master, initiating repl-timeout every 10s 60 # Setup Slave ping does not pass the master number of S after the timeout repl-disable-tcp-nodelay no # will use less bandwidth, but there will be a delay, It is recommended to close the repl-backlog-size 1mb # master-slave Disconnect, the master first writes the data to the buffer Backuplog, Once again the connection is read from the data repl-backlog-ttl 3600 # after the master-slave disconnection, the buffer expires, Default 1-hour slave-priority 100 # multiple slave set priority, The smaller the value the higher the priority, which is used in the cluster,min-slaves-to-write 3 # and the following The main discovery has more than 3 slave delay than the 10s,min-slaves-max-lag 10 #那么主就会暂停写操作. If either of these values is 0, the feature is turned off
Common commands
String
Set Key1 Teng//Set Assignment
Set Key1 Teng//A key corresponds to a value, multiple assignments, overwriting the previous value
Get Key1//Get Fetch value
SETNX Key2 AAA//return 1,get Key2 View
SETNX key2 BBB//returns 0, if key is present, returns 0, does not create
Setex Key3 10 1//This is the viewing time TTL used to set the expiry time for the key Key3
Mset Key1 1 Key2 2 C 3//Set multiple keys simultaneously
Mget Key1 Key2 C
Hash:
Hset user1 name Teng//build hash, can store user name sex age and so on more information
Hset User1 age 24
Hset User1 Job It
Hgetall user1//Get all values
Hmset user2 Name Teng Age job IT//bulk build key value pair
Hmget user2//Get all values
Hmget user2 name Age//Get specified value
Hdel user2 Job//delete specified filed
Hkeys User2//Print all keys
Hvals User2//Print all values
Hlen user2//view hash has several filed (keys), return number
Lists
Lpush lista A//pressing an element from the left
Lpush lista b
Rpush lista 1//Pressing an element from the right
Rpush Lista 2
Lpop lista//From the left, the default left first, when removed, this value will not exist
Rpop lista//Take the first element from the right
Lrange lista 0-1//0 for head left first,-1 for tail right first, no rrange
Linsert lista before 2 3//Insert an element in front of the value 2 of the element as 3
LSet lista 4 bbb//change 5th element to BBB
Lindex lista 0//view 1th element, number is index
Lindex lista 3//view 4th element
Llen lista//View a list of several elements
Set
Sadd Seta AAA//Put elements into the collection Seta
Smembers Seta//View all elements in a collection
Srem Seta AAA//delete element
Spop Seta//randomly take out an element, delete
Sdiff Seta SETB//differential set, Seta as standard
Sinter Seta SETB//Seek intersection
Sunion Seta SETB//Request and set
Sdiffstore setc Seta SETB//differential set, and stored in setc, view Smembmers setc
Sinterstore setd seta SETB//ask for intersection and store setd, view Smembmers setd
Sunionstore Sete Seta SETB//set, and stored to Sete
Sismember Seta AAA//Determine if an element belongs to a collection
Srandmember Seta//random extraction of an element without deleting
Zset:
Zadd Zseta 11 123//Create ordered collection, uppercase Zadd and other commands can be tab-complete
Zrange Zseta 0-1//Show all elements in order
Zrange Zseta 0-1 withscores//can bring the score
Zrangebyscore Zseta 1 10//Return the element of the score range 1-10
Zrank Zseta 222//Returns the index value of the element, starting from 0, sorted by score
Zrevrank Zseta 222//Ibid, different, sorted by score reverse order
Zrevrange Zseta 0-1//reverse order display all elements with a score
Zcard Zseta//Returns the number of all elements in the collection
Zcount Zseta 1 10//Returns the number of elements in the score range 1-10
Zrem Zseta 222//delete specified element
Zremrangebyrank Zseta 0 2//delete element of index range 0-2, sort by score
Zremrangebyscore Zseta 1 10//Delete the element of the score range 1-10
Key-Value Related:
Keys *//Remove all keys
Keys m*//fuzzy matching
EXPIRE Key1 100//Set Key1 expires after 100s
Del Key1//Deletes a key, returns 1 successfully, otherwise returns 0;
How long does the TTL key//View key expire, either s,-2 or key does not exist, 1 has no time to live
Select 0//represents selecting the current database and entering the 0 database by default
exists name//has the name key to return 1, otherwise returns 0;
Move age 1//moves age to 1 database
Persist Key1//Cancel the expiration time of the Key1
Randomkey//Randomly returns a key
Type key1//types of return keys
Rename oldname newname//rename key
Info//Return Redis database status information
Dbsize//Returns the number of keys in the current database
FLUSHDB//empties all keys in the current database
Flushall//Clears all keys from all databases
-------------------------------------------------------------------------------------------------
This article is from the "North Ice--q" blog, please be sure to keep this source http://beibing.blog.51cto.com/10693373/1875149
NoSQL-Redis Installation Master-slave configuration detailed commands