Brief introduction
Redis is a key-value storage system. Similar to memcached, it supports storing more value types, including string (string), list (linked list), set (set), and Zset (ordered collection). These data types are supported by Push/pop,add/remove and intersection sets and difference sets and richer operations, and these operations are atomic in nature. Based on this, Redis supports sorting in a variety of different ways. As with memcached, data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to disk or writes the modified operation to the appended record file, and Master-slave (Master-Slave) synchronization is implemented on this basis.
Redis is a high-performance Key-value database, the emergence of redis to a large extent to compensate for memcached such key/value storage deficiencies, in some cases can be a good complement to the relational database, it provides Python,ruby, erlang,php client, very convenient to use.
ACID
ACID, which is an abbreviation for the four basic elements that the database transaction performs correctly. Contains: atomicity (atomicity), consistency (consistency), isolation (isolation), persistence (durability). A support transaction (Transaction) database system, must have these four characteristics, otherwise in the transaction process (Transaction processing) can not guarantee the correctness of the data, the transaction process is very likely not to reach the requirements of the counterparty.
Atomic Nature
All operations in the entire transaction, either complete or incomplete, are not likely to stall in one part of the middle. When an error occurs during execution, the transaction is rolled back (Rollback) to the state before the transaction begins, as if the transaction had never been executed.
Consistency
The integrity constraints of the database are not compromised until the transaction begins and after the transaction has ended.
Isolation of
The execution of two transactions is non-disruptive, and one transaction cannot see the data in the middle of a time when other transactions are running.
Durability
After the transaction is completed, the changes made to the database by the firm persist in the database and are not rolled back.
Specific operation:
1. install redis and decorate the environment (specify background run) # tar -zxvf redis-2.4.17.tar.gz decompression # cd redis-2.4.17 Enter directory # make compile # make prefix=/usr/local/redis install The specified directory installation # cd /usr/local/redis/ into the installed directory # mkdir etc logs Create a new two directory # cd etc# cp /lamp/redis-2.4.17/redis.conf /usr/local/redis/etc/ Copying a configuration file # cd etc/# vi redis.conf Modify configuration file: Open background run, specify log file. daemonize yes Open Background Run logfile /usr/local/ redis/logs/redis.log specifies the log file. # ./redis-server /usr/local/redis/etc/redis.conf Start # ps -ef | grep redis View Process # netstat -tunpl | grep 6379 View Port # ./redis-cli Client Command link Server redis 127.0.0.1:6379> redis 127.0.0.1:6379>quit Exit # pkill redis-server to end the Redis process. or: # ./redis-cli shutdown execution shutdown
Data types for Redis
1. Total 5 types: String (string), hashes type, list (doubly linked list), set (set), and Zset (ordered collection)
2. String (substring type)
Set command: Sets a key and value, the key exists only overwrite, return ok > set key value for example: >set name zhangsan get command: Gets the value of a key, return value > get key such as:>get name SETNX command: Sets a nonexistent key and value (prevents overwriting), > setnx key value returns 0 if the key already exists setex command: Sets a key and value (in seconds) for a specified validity period > setex key [Effective Time] value for example: >setex color 10 red Do not write valid time is permanent valid, equivalent to Set setrange command: Replace substring (replacement length is determined by substring length) > setrange Keys Locations substrings > setrange name 4 aa replaces the 4th position of the name key corresponding to the mset command: Bulk set key and value, success returns ok > mset key 1 value 1 key 2 value 2 key 3 Value 3 ....     MSETNX command: Bulk set non-existent keys and values, Success returns OK   > MSETNX Key 1 value 1 key 2 value 2 key 3 value 3 .... getset command: Get the original value and set the new value getrange command: Gets the value of the specified range >getrange key 0 4 //gets the value at the specified 0 to 4 position mget command: bulk Fetch value >mget key 1 2 Key 3....     INCR command: Specify the value of the key to do the Gaga operation, return the result after adding. > incr keys such as: >incr Kid incrby command: set a key plus the specified value > incrby key m //where m can be a positive integer or a negative integer    DECR command: The value of the specified key to do the subtraction operation, returning the result of the subtraction. > decr keys such as: >decr Kid decrby command: set a key minus the specified value > decrby key m //where m can be a positive integer or a negative integer append command: Appends value to the string of the specified key, returning the length of the new string value >append key Append string ha strlen for length >strlen key name //returns the corresponding value.
3. Hashes type
Hset command: Set the key and value of a hash table >hset hash name key value such as: >hset user:001 name Zhangsan hsetnx command: Set a hash table does not exist in the key and value >HSETNX hash name key value//into Work returns 1, failure returns 0 such as: >hsetnx user:001 name zhangsanhmset command: Bulk set hget command: Gets the value of the key corresponding to the hash name in the execution >hexists user:001 name//Whether there is a return 1 >hlen user:001//Gets the number of keys in a hash user001 name >hdel user:001 name//delete hash user:001 in name key >hkeys user:002//return hash named user:002 All the keys. >hvals user:002//Returns all values in the hash named user:002. >hgetall user:002//Returns all keys and values in the hash named user:002.
4. The list type (doubly linked list structure)
List is available as a "stack" or as a "queue".
Action:
>lpush list1 "World" //a string >lpush list1 "Hello" in List1 head // List1 the head into a string >lrange list1 0 -1 //get List1 content 0: The beginning of the -1 represents the end. >rpush list2 "World" //a string in the tail of List2 >rpush list2 "Hello" // press a string at List2 tail >lrange list2 0 -1 //get List2 content 0: Represents the beginning of the -1 to indicate the end. >linsert list2 before "Hello" "There" adds a string before or after the key corresponds to a specific position in the list >lset list2 1 "Four" modifies the value at the specified index location >lrem list2 2 "Hello" // Delete the first two hello values >lrem list2 -2 "Hello" //after deleting the two hello values >lrem list2 0 "Hello" //Delete all Hello values >ltrim mylist8 1 -1 //remove values outside this range >lpop list2 //removes the element from the List2 's head and returns the delete element >RPOP&NBsp;list2 //removes the element from the tail of List2 and returns the delete element >rpoplpush list1 list2 //moves an element of the List1 's tail out to the List2 head. and returns >lindex list2 1 //returns the element on the index position in List2 >llen list2 //returns the List2 length
5.sets Types and operations
>sadd myset "Hello"//Add an element to MySet successfully returns 1, fails (repeats) return 0>smembers MySet//Get all elements in MySet >srem myset "one"// Remove one of the MySet from a successful return 1, failure (not present) returns 0 >spop myset//random return and delete one element in MySet >sdiff myset1 Myset2//Returns two sets of differences with MYSET1 as standard, Gets the Myset2 that does not exist in the. >sdiffstor
Redis Common Commands
1. Key-Value related commands
>keys *//Return key (key) >keys list*//Returns the name of all keys (key) that begin with List >exists List1//Determine if the key named List1 is present, returns 1, does not exist return 0>de L List1//delete a key (named List1) >expire List1 10//Set key named List1 expires in 10 seconds after >ttl List1//view key named List1 Expiration time, if 1 means expire >move Age 1//Transfers the key name age to the 1 database. >select 1//= Enter into 1 database, default at 0 database >persist age//Remove aging (set to expire)
Redis Advanced Utility Features
1. Security: Add a password for Redis
1. Enter the configuration file:
Requirepass Redis's password
2. Restart the service:
#./REDIS-CLI Shutdown Execution shutdown
#./redis-server/usr/local/redis/etc/redis.conf Start
3. Login (two types)
#./REDIS-CLI Client Command Link server
>auth Password value//authorized to use the rear
#./redis-cli-a Password//Specify password to authorize when connecting
2. master-slave replication
Operation Steps:
1. Shut down the Linux virtual machine first, then clone one.
2. Start two virtual machines: Master (Master) and Slave (from)
3. Configure the IP address in slave (from)
# ifconfig Eth0 192.168.128.229
# ping it and see how it's not through.
4. Configure the Slave machine
Enter: Profile
slaveof 192.168.128.228 6379 //Configure the IP and port of the Redis for the connection host
Masterauth password //configure connection Password
Finally, start the Redis service on the Slave (slave) machine.
Other: You can view your role as Master, slave, through the roles property in the info command
3. Transaction processing
>multi//Open a transaction
>set age 10//Staging command queue
>set age 20
>exec//Start Execution (COMMIT transaction)
or >discard//empty command queue (transaction rollback)
4. Optimistic lock
Make one of the manipulated properties before the transaction:
> Watch Age
>multi//Open a transaction (there are other modifications during this time, it will fail here)
>set age 10//Staging command queue
>set age 20
>exec//Start Execution (COMMIT transaction)
or >discard//empty command queue (transaction rollback)
5. Persistence mechanism
1. snapshotting (snapshot) default mode
Configure Save
Save 1 #900秒内如果超过1个key被修改 to initiate a snapshot save
Save #300秒内容如超过10个key被修改, the snapshot save is initiated
Save 60 10000
2. append-only file (aof mode)
Config appendonly on change to Yes
Generates a. aof file in the bin directory
About the configuration of aof
AppendOnly Yes//enable 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
6. Publish and subscribe to messages
Need to open multiple session ports
Session 1:>subscribe TV1//monitor TV1 Channel
Session 2:>subscribe TV1 TV2//monitoring TV1 and TV2 channels
Session 3: >publish TV1 message//Send a message to TV1 channel
7. Using Virtual memory
Set up in the Redis configuration file
vm-enabled Yes #开启vm功能
Vm-swap-file/tmp/redis.swap #交换出来的value保存的文件路径
Vm-max-memory 1000000 #redis使用的最大内存上限
Vm-page-size #每个页面的大小32字节
Vm-pages 134217728 #最多使用多少页面
Vm-max-threads 4 #用于执行value对象换入患处的工作线程数量
Introduction to Redis and common operations