String类型
简介
string类型是Redis最基本的数据类型,一个键最大能存储512MB。
string数据结构是最简单的key-value类型,value不仅可以是string,也可以是数字,是包含很多种类型的特殊结构类型。
string类型是二进制安全的。意思是redis可以包含任何数据。比如序列化的对象进行存储,比如一张图片进行二进制存储,再比如一个简单的字符串,数值等等。
String命令
赋值语法:
一、SET key value [EX seconds|PX milliseconds] [NX|XX] [KEEPTTL]
SET 命令用于设置给定 key 的值。如果 key 已经存储值, SET 就覆写旧值,且无视类型 。
Options
The SET command supports a set of options that modify its behavior:
- EX seconds – Set the specified expire time, in seconds.
- PX milliseconds – Set the specified expire time, in milliseconds.
- NX – Only set the key if it does not already exist.
- XX – Only set the key if it already exist.
- KEEPTTL – Retain the time to live associated with the key.
Examples
127.0.0.1:6379> set name dsy
OK
127.0.0.1:6379> get name
"dsy"
127.0.0.1:6379> set age 23 EX 10 //有效期为60秒
OK
127.0.0.1:6379> keys * //立刻查询
1) "name"
2) "age"
127.0.0.1:6379> keys * //过一会查询
1) "name"
二、SETNX key value
如果键不存在,则将键设置为value值,在这种情况下,它等于SET。当键已经具有值时,将不执行任何操作。 SETNX是“ SET if Not eXists”的缩写。
返回值
- 0:如果key之前已经被set
- 1:如果key之前不存在
Examples
127.0.0.1:6379> setnx key1 hello
(integer) 1
127.0.0.1:6379> setnx key1 world
(integer) 0
127.0.0.1:6379> get key1
"hello"
三、SETEX key seconds value
将值 value 关联到 key ,并将 key 的过期时间设为 seconds (以秒为单位)。如果 key 已经存在, SETEX 命令将会替换旧的值。
Examples
127.0.0.1:6379> keys *
1) "name"
2) "key1"
127.0.0.1:6379> setex name 10 aaa
OK
127.0.0.1:6379> get name
"aaa"
127.0.0.1:6379> get name
(nil)
四、SETRANGE key offset value
用指定的字符串覆盖给定 key 所储存的字符串值,覆盖的位置从偏移量 offset 开始。
返回值: 被修改后的字符串长度。
Examples
127.0.0.1:6379> set name hello world
(error) ERR syntax error
127.0.0.1:6379> set name "hello world"
OK
127.0.0.1:6379> setrange name 6 redis
(integer) 11
127.0.0.1:6379> get name
"hello redis"
取值语法:
一、GET key
Redis Get 命令用于获取指定 key 的值。如果 key 不存在,返回 nil 。如果key 储存的值不是字符串类型,返回一个错误。
Examples
127.0.0.1:6379> keys *
1) "name"
2) "key1"
127.0.0.1:6379> get name
"hello redis"
127.0.0.1:6379> get key1
"hello"
127.0.0.1:6379> get aaa
(nil)
二、GETRANGE key start end
Redis Getrange 命令用于获取存储在指定 key 中字符串的子字符串。字符串的截取范围由 start 和 end 两个偏移量决定(包括 start 和 end 在内)。
Examples
127.0.0.1:6379> get name
"hello redis"
127.0.0.1:6379> getrange name 6 10
"redis"
三、GETSET key value
Redis Getset 命令用于设置指定 key 的值,并返回 key 旧的值。
Examples
127.0.0.1:6379> set number 9
OK
127.0.0.1:6379> incr number
(integer) 10
127.0.0.1:6379> getset number 8
"10"
127.0.0.1:6379> get number
"8"
三、STRLEN key
Redis Strlen 命令用于获取指定 key 所储存的字符串值的长度。当 key 储存的不是字符串值时,返回一个错误。
Examples
127.0.0.1:6379> get name
"hello redis"
127.0.0.1:6379> strlen name
(integer) 11
删除语法:
DEL key
Redis DEL 命令用于删除已存在的键。不存在的 key 会被忽略。
Examples
127.0.0.1:6379> keys *
1) "number"
2) "name"
3) "key1"
127.0.0.1:6379> del number
(integer) 1
127.0.0.1:6379> del number
(integer) 0