Through the introduction in the last two articles, our redis server basically runs. All databases have the most basic CRUD functions. along this context, we start to learn about the rich data structures of redis. Of course, we should first start with the simplest and most commonly used string.
Redis series-Remotely connect to redis and lock redis
Redis series-installation, deployment, and maintenance
1. New
A) set
Syntax: set key value
Explanation: Assign the value to the key. If the key does not exist, add the value. Otherwise, update the value.
[Root @ bkjia001 ~] # Redis-cli
Redis 127.0.0.1: 6379> set user.1.name zhangsan # set user.1.name to zhangsan
OK
Redis 127.0.0.1: 6379> set user. name 45 # set user.1.name to 45
OK
B) setnx
Syntax: setnx key value
Explanation: If only insert is not updated, that is, if only the key does not exist, the key value is set to value and 1 is returned. Otherwise, 0 is returned. Setnx is the abbreviation of set if not exists.
Redis 127.0.0.1: 6379> setnx user.1.name zhangsan # user.1.name already exists, 0 is returned
(Integer) 0
Redis 127.0.0.1: 6379> setnx user.2.name zhangsan # user.2.name does not exist, Set
(Integer) 1
C) setex
Syntax: setex key seconds value
Explanation: Set the key expiration time and value. The expiration time in seconds. Setting the expiration time and value is an atomic operation. This command is useful if redis is only used as a cache.
Redis 127.0.0.1: 6379> setex user.2.age 2 14 # Set the user.2.age value to 14 and expire after 2 seconds
OK
Redis 127.0.0.1: 6379> get user.2.age # Before Expiration
"14"
Redis 127.0.0.1: 6379> get user.2.age # after expiration
(Nil)
D) mset
Syntax: mset key value [key value...]
Explanation: Multiple key-values are set at the same time.
Redis 127.0.0.1: 6379> mset user.4.name lisi user.4.age 34 # Set user.4.name = lisi, user.4.age = 34
OK
Redis 127.0.0.1: 6379> get user.4.name
"Lisi"
Redis 127.0.0.1: 6379> get user.4.age
"34"
E) msetnx
Syntax: msetnx key value [key value...]
Explanation: The set operation is performed only when all keys do not exist.
Redis 127.0.0.1: 6379> msetnx user.4.name lisi user.4.age 34 # Keys have been set and cannot be set again
(Integer) 0
Redis 127.0.0.1: 6379> msetnx user.4.name lisi user.4.std 3 # key user.4.name has been set and cannot be set again
(Integer) 0
Redis 127.0.0.1: 6379> msetnx user.4.tech lisi user.4.std 3 # the key has not been set. You can set it again.
(Integer) 1