Introduction to Redis
Redis is completely open source and free, and is a high-performance key-value database.
Redis and other key-value cache products have the following three characteristics:
- Redis supports data persistence, which can save the data in the memory to the disk, and load it again when restarting.
- Redis not only supports simple key-value type data, but also provides storage of data structures such as list, set, zset, and hash.
- Redis semi-persistent, stored in memory and hard disk
The difference between Redis and MongoDB:
- Redis is a database that stores data completely in memory. It only uses disks for persistence purposes and regularly writes them to disks. When the memory is insufficient, you can choose the specified LRU algorithm to delete data. Persistence uses RDB or aof methods.
- mongodb is a document-type non-relational database, similar to MySQL, which supports field indexing and cursor operations. Its advantage is that it has a relatively powerful query function, is good at querying JSON data, and can store massive data, but does not support transactions.
Redis download and configuration
Download Address 1
Download link 2
After downloading and decompressing, enter the file redis.windows.conf
Set the database password on line 387
Modify the size of the maximum data heap (unit: byte)
Modify at line 469
Note: Add a line below the configuration file maxXXXX
Start the Redis database
Start the redis database server
Enter the file path in the command prompt window, and enter the following command:
redis-server.exe redis.windows.conf # Execute redis-server.exe and load the Windows configuration file
As shown in the figure, it means that the server starts successfully, and the window needs to be saved, and the server will be automatically closed when it is closed.
The client connects to the redis database
Open a command prompt in the file directory and enter the command:
redis-cli.exe
The format of the input password is (the quotation marks must be added, because it is a string type):
auth 'your password'
Type of Redis value
-
String String
-
hash hash
-
list list
-
Collection set
-
ordered set zset
Redis operation command
All commands for data operations: http://redis.cn/commands.html
View all databases:
config get databases
View all databases, databases start with 0, a total of 16
Select database:
select 1 #Enter database 1
Defaults to database 0
select num to switch the database
1. String
String is the most basic type of redis, which can store up to 512MB of data. The String type is binary safe, that is, it can store any data, such as numbers, pictures, serialized objects, etc.
A key corresponds to a value
1. Set key value
A. Set key value
set key value
set name "zhangsan"
B. Set the key value and expiration time, in seconds
setex key seconds value
setex name 10 'zhangsan'
C. Check the effective time, in seconds
ttl key
ttl name
D. Cancel expiration time
persist key
persist name
E. Set the value of the key only when the key does not exist
setnx key value
setnx name 'a'
E. Set multiple key values
mset key value [key value…]
mset name 'zs' age 18
2. Key operation
A. Get the value according to the key, if the key does not exist, return None(null 0 nil)
get key
get name
B. Get multiple values based on multiple keys
mget key [key…]
mget name age
C, return the subcharacter of the string value in the key
get range key start end
getrange name 0 4
D. Set the value of the given key to value and return the old value of the key (old value)
getset key value
getset name 'x'
3. Operation
Requirement: the value is a number of string type
A. Add 1 to the value corresponding to the key
incr key
incr age
B. Decrease the value corresponding to the key by 1
decr key
decr age
C. Add an integer to the value corresponding to the key
incrby key intnum
incrby age 10
D. Subtract the value corresponding to the key by an integer
decrby key intnum
decrby age 10
E, get value length
strlen key
strlen age
Key operation
A. Find all keys
keys*
B. Determine whether the key exists, if it exists, return 1, if it does not exist, return 0
exists key
exists name
C. View the value type corresponding to the key
type key
type name
D, delete key and corresponding value
del key [key…]
E. Set the expiration time in seconds
expire key seconds
expire age 10
F. Check the effective time, in seconds
ttl key
H, returns the remaining expiration time of the key in milliseconds
pttl key
I. Remove the expiration time of the key, and the key will remain persistent
persist key
J. Delete all keys
flushdb deletes all
flushall deletes all keys in the database
K. Modify the name of the key (rename the key to newkey only when newkey does not exist)
rename key newkey
L, move the key to the specified database
Move key db
move name 1 # move name to database 1
M. Randomly return a key
random key
Two, hash
hash is used to store objects
{
?name: “tom”,
? age: 18
}
Redis hash is a collection of key-value (key=>value) pairs.
1. Settings
a. Set a single value
hset key field value
redis> hset myhash name lucky (integer) 1 redis> HGET myhash name "Hello"
b. Set multiple values
hmset key field value [field value…]
hmset myhash a 1 b 2 c 3
C adds increment to the integer value of the specified field in the hash table key
hincrby key field incrment
hincrby hh age 10
D Only when the field field does not exist, set the value of the hash table field
hsetnx key field value
hget hh name
2. Get
A. Get the value of an attribute
hget key field
hget name field1
B. Get the value of multiple attributes
hmget key filed [filed…]
C. Get all fields and values
hgetall key
D. Get all fields
hkeys key
E. Get all values
hvals key
F, return the number of data contained
hlen key
3. Other
A. Determine whether the attribute exists, return 1 if it exists, and return 0 if it does not exist
hexists key field
hexists a x
B. Delete fields and values
hdel key field [field…]
hdel a x y z
C, the string length of the return value, starting from version 3.2
hstrlen key field
3. List list
Redis lists are simply lists of strings, sorted by insertion order. You can add an element to the head (left) or tail (right) of the list
1. Settings
A, insert at the head
lpush key value [vlaue…]
lpush demo 2 3`
Insert a value into the head of an existing list, the operation is invalid when the list does not exist
Lpushx key val
lpushx list 'a'
B. Insert at the end
rpush key value [vlaue…]
rpush demo 2 1
Add value to an existing list
rpushx key val
rpushx mm 'a'
2. Get
A, remove and return the first element of the list corresponding to the key
lpop key
lpop demo
B. Remove and return the last element of the list corresponding to the key
rpop key
rpop demo
C. Return the elements of the specified range stored in the key list
lrange key start end
lrange demo 0 -1 #View all elements in the list
Note: start end starts from 0
Note: Offset can be negative
3. Other
A, cut list, change to a subset of the original set
ltrim key start end
ltrim demo 1 -1 #Cut out the elements with index 1 to -1
Note: start end starts from 0
Note: Offset can be negative
B. Return the length of the list stored in the key
llen key
C. Return the value corresponding to the index in the list
lindex key index
LINDEX mylist 0
Fourth, collection set
Unordered collection, the element type is String type, and the elements are unique and not repeated
{‘a’,’b’}
1. Settings
A, add elements
sadd key member [member…]
sadd set 'a' 'b' 'c'
2. Get
A. Return all elements in the key collection
smembers key
smembers set
B. Return the number of collection elements
card key
scard set
C, remove and return a random element in the collection
spop key
spop set
D. Return one or more random numbers in the collection
srandmember key count
s set #return a random element srandmember set 2 #return 2 random elements
E. Remove one or more members from the set
srem key member1 [memkber2]
srem set 'd' 'b'ss
3. Other operations of collection
A. Find the intersection of multiple sets
sinter key [key …]
sinter m l # Find the intersection of set l and set m
B. Find the difference of multiple sets
sdiff key [key…]
sdiff m l #Seek the difference set Pay attention to the order of comparison
D. Determine whether the element is in the set, return 1 if it exists, and return 0 if it does not exist
sismember key member
sissmember m 'a' #Whether element 'a' exists in set m
5. Ordered collection zset
- An ordered collection, the element type is String, and the elements are unique and cannot be repeated
- Each element will be associated with a double type score (indicating weight), sorted by the size of the weight, the score of the elements can be the same
1. Settings
A, Add
zadd key score member [score member…]
zadd zset 1 a 5 b 3 c 2 d 4 e
B. In the ordered set, add increment to the score of the specified member
Zincrby key increment mcfaember
zincrby zset 10 'a' #Add 10 to the weight of a
2. Get
A, return the elements of the specified range
zrange key start end
zrange z1 0 -1
B, return the number of elements
zcard key
zcard z1
C. Return the number of elements whose score is between min and max in the ordered set key
zcount key min max
D. Return the score value of the member member in the ordered set key
zscore key member
zscore l 'c' #s returns the weight of c
E, all values and weights of the current collection
ZRANGE key 0-1 WITHSCORES
F. Return the members in the specified score range in the ordered set, and the scores are sorted from low to high
ZRANGEBYSCORE key min max [WITHSCORES][LIMIT offset count]
interval and infinity
min and max can be -inf and +inf, so that you can use commands like ZRANGEBYSCORE without knowing the lowest and highest score values of the sorted set.
redis> ZADD myzset 1 "one" (integer) 1 redis> ZADD myzset 2 "two" (integer) 1 redis> ZADD myzset 3 "three" (integer) 1 redis> ZRANGEBYSCORE myzset -inf + inf 1) "one" 2) "two" 3) "three" redis> ZRANGEBYSCORE myzset 1 2 1) "one" 2) "two"
3. Delete
A removes one or more members from the sorted set
When the key exists, but it is not an ordered collection type, an error is returned.
ZREM key member [member…]
redis> ZADD myzset 1 "one" (integer) 1 redis> ZADD myzset 2 "two" (integer) 1 redis> ZADD myzset 3 "three" (integer) 1 redis> ZREM myzset "two" (integer) 1 redis> ZRANGE myzset 0 -1 WITHSCORES 1) "one" twenty one" 3) "three" 4) "3" redis>
Password security
Check whether password authentication is set. By default, the requirepass parameter is empty, indicating that you can connect to the redis service without password authentication.
CONFIG get requirepass
change Password
CONFIG set requirepass "123"
After setting the password, the client needs password verification to connect to the redis service, otherwise the command cannot be executed
Redis data backup and recovery
Create a backup of the current database
SAVE
This command will create a dump.rdb file in the redis installation directory.
Restore data
If you need to restore data, just move the backup file (dump.rdb) to the redis installation directory and start the service.
To get the redis directory, you can use the following command:
CONFIG GET dir
Backup data
use command
BGSAVE
Python operation redis
Install
pip install redis
example
import redis # Ordinary connection StrictRedis is recommended # decode_responses=True to automatically decode # The default database is 0 r = redis.Redis(host='127.0.0.1',port=6379,password='123c456',db=0,decode_responses=True) r = redis.StrictRedis(host='10.10.2.14',port=6379,password='123456',decode_responses=True) # connection pool """ Manage all connections to a redis server, avoiding the overhead of establishing and releasing connections each time. Each redis instance will maintain its own connection pool. You can directly create a connection pool and pass it to redis as a parameter, so that multiple redis instances can share a connection pool. """ pool = redis.ConnectionPool(host='127.0.0.1',port=6379,db=0,password='123456',decode_responses=True) r = redis.Redis(connection_pool=pool) # string # set up print(r. set("name", "sea")) print(r. get('name')) # Batch settings print(r.mset({<!-- -->'name':'sea', 'age': 18})) print(r. mget('name', 'age')) # hash # set up print(r.hset("hash", "name", "sea")) print(r. hget("hash", "name")) # get all print(r. hgetall('hash')) # Batch settings print(r.hmset("myhash",{<!-- -->"name":"sea", "age": 18})) # Get all hash fields print(r.hkeys("myhash")) # Get all the values of the hash print(r.hvals('myhash')) # list # set up print(r.lpush('list', 1, 2, 3)) print(r.rpush('list', 4, 5, 6)) # Obtain print(r. lrange('list', 0, -1)) # number of elements print(r. llen('list')) # set # add value print(r. sadd('set1', 'a', 'b', 'c')) print(r. sadd('set2', 'a', 'b', 'd')) # get value print(r. smembers('set1')) # number of elements print(r. scard('set1')) # orderly set # add value print(r.zadd('zadd', {<!-- -->"a": 1, 'b': 2, 'c': 3})) print(r. zcard('zadd')) # return weight print(r. zscore('zadd', 'a'))