Redis字符串String #

一、字符串概述 #

1.1 什么是字符串 #

字符串是Redis最基础的数据类型,可以存储:

  • 文本字符串
  • 整数
  • 浮点数
  • 二进制数据(如图片、序列化对象)
text
字符串存储结构:

┌─────────────────────────────────────────────┐
│  Key         │  Value                       │
├──────────────┼──────────────────────────────┤
│  name        │  "John"                      │
│  age         │  "25"                        │
│  price       │  "99.99"                     │
│  binary      │  "\x00\x01\x02..."           │
└─────────────────────────────────────────────┘

最大大小:512MB

1.2 字符串编码 #

text
Redis字符串的三种编码:

1. int(整数)
   ┌─────────────────────────────────────────────┐
   │ 存储整数,范围在long范围内                  │
   │ 节省内存                                    │
   │ SET counter 100                            │
   └─────────────────────────────────────────────┘

2. embstr(嵌入式字符串)
   ┌─────────────────────────────────────────────┐
   │ 短字符串,长度≤44字节                       │
   │ 内存连续分配,效率高                        │
   │ SET name "John"                            │
   └─────────────────────────────────────────────┘

3. raw(原始字符串)
   ┌─────────────────────────────────────────────┐
   │ 长字符串,长度>44字节                       │
   │ 使用SDS(Simple Dynamic String)           │
   │ SET text "很长的字符串内容..."              │
   └─────────────────────────────────────────────┘

二、基本操作 #

2.1 设置和获取 #

bash
# 设置值
SET key value

# 示例
SET name "John"
# OK

# 获取值
GET name
# "John"

# 获取不存在的键
GET notexist
# (nil)

# 设置多个值
MSET key1 "value1" key2 "value2" key3 "value3"
# OK

# 获取多个值
MGET key1 key2 key3
# 1) "value1"
# 2) "value2"
# 3) "value3"

# 设置并返回旧值
GETSET name "Mike"
# "John"  返回旧值
GET name
# "Mike"

2.2 设置选项 #

bash
# EX: 设置过期时间(秒)
SET session "data" EX 3600
# 3600秒后过期

# PX: 设置过期时间(毫秒)
SET session "data" PX 3600000
# 3600000毫秒后过期

# EXAT: 设置过期时间戳(秒)
SET session "data" EXAT 1700000000

# PXAT: 设置过期时间戳(毫秒)
SET session "data" PXAT 1700000000000

# NX: 键不存在时设置
SET lock "value" NX
# OK  如果键不存在
# (nil)  如果键已存在

# XX: 键存在时设置
SET name "John" XX
# OK  如果键存在
# (nil)  如果键不存在

# 组合使用
SET lock "value" NX EX 30
# 分布式锁常用模式

# KEEPTTL: 保留原有过期时间
SET name "John" KEEPTTL

2.3 特殊设置命令 #

bash
# SETEX: 设置值和过期时间(秒)
SETEX session 3600 "data"
# 等价于 SET session "data" EX 3600

# PSETEX: 设置值和过期时间(毫秒)
PSETEX session 3600000 "data"

# SETNX: 键不存在时设置
SETNX lock "value"
# (integer) 1  设置成功
# (integer) 0  键已存在,设置失败

# SETNX + EXPIRE 组合(不推荐,非原子)
SETNX lock "value"
EXPIRE lock 30

# 推荐使用 SET NX EX
SET lock "value" NX EX 30

三、字符串操作 #

3.1 追加和长度 #

bash
# 追加内容
SET greeting "Hello"
APPEND greeting " World"
# (integer) 11  返回新长度
GET greeting
# "Hello World"

# 对不存在的键追加(相当于SET)
APPEND newkey "value"
# (integer) 5
GET newkey
# "value"

# 获取字符串长度
STRLEN greeting
# (integer) 11

STRLEN notexist
# (integer) 0

3.2 获取子串 #

bash
# GETRANGE: 获取子串
SET text "Hello World"
GETRANGE text 0 4
# "Hello"

GETRANGE text 6 -1
# "World"

GETRANGE text -5 -1
# "World"

# 注意:GETRANGE不会修改原字符串

3.3 设置子串 #

bash
# SETRANGE: 替换子串
SET text "Hello World"
SETRANGE text 6 "Redis"
# (integer) 11
GET text
# "Hello Redis"

# 超出范围会填充空字节
SET text "Hello"
SETRANGE text 10 "World"
# (integer) 15
GET text
# "Hello\x00\x00\x00\x00\x00World"

四、数值操作 #

4.1 自增自减 #

bash
# INCR: 自增1
SET counter 10
INCR counter
# (integer) 11

# 对不存在的键自增(从0开始)
INCR newcounter
# (integer) 1

# INCRBY: 增加指定值
INCRBY counter 10
# (integer) 21

# INCRBYFLOAT: 增加浮点数
SET price 10.5
INCRBYFLOAT price 0.5
# "11"

INCRBYFLOAT price -2.5
# "8.5"

# DECR: 自减1
DECR counter
# (integer) 20

# DECRBY: 减少指定值
DECRBY counter 5
# (integer) 15

4.2 数值操作注意事项 #

bash
# 只能对整数进行INCR/DECR
SET text "hello"
INCR text
# (error) ERR value is not an integer or out of range

# INCRBYFLOAT可以对整数和浮点数操作
SET num 10
INCRBYFLOAT num 0.5
# "10.5"

# 数值范围:64位有符号整数
# 最小值:-9223372036854775808
# 最大值:9223372036854775807

五、位操作 #

5.1 位操作命令 #

bash
# SETBIT: 设置位
SETBIT bitmap 0 1
# (integer) 0  返回旧值

SETBIT bitmap 1 1
SETBIT bitmap 2 0
SETBIT bitmap 3 1

# GETBIT: 获取位
GETBIT bitmap 0
# (integer) 1

GETBIT bitmap 2
# (integer) 0

# BITCOUNT: 统计1的个数
SETBIT bitmap 0 1
SETBIT bitmap 1 1
SETBIT bitmap 2 0
SETBIT bitmap 3 1
BITCOUNT bitmap
# (integer) 3

# 统计指定范围
BITCOUNT bitmap 0 1
# (integer) 2

# BITPOS: 查找第一个0或1的位置
BITPOS bitmap 1
# (integer) 0  第一个1的位置

BITPOS bitmap 0
# (integer) 2  第一个0的位置

5.2 位运算 #

bash
# BITOP: 位运算
SET key1 "\xff"   # 11111111
SET key2 "\x0f"   # 00001111

# AND 与运算
BITOP AND result key1 key2
# (integer) 1
GET result
# "\x0f"  # 00001111

# OR 或运算
BITOP OR result key1 key2
# (integer) 1
GET result
# "\xff"  # 11111111

# XOR 异或运算
BITOP XOR result key1 key2
# (integer) 1
GET result
# "\xf0"  # 11110000

# NOT 非运算
BITOP NOT result key1
# (integer) 1
GET result
# "\x00"  # 00000000

5.3 位图应用场景 #

bash
# 用户签到(一年365天,每天一位)
# 用户ID为1001,第100天签到
SETBIT user:1001:sign:2024 99 1

# 检查第100天是否签到
GETBIT user:1001:sign:2024 99
# (integer) 1

# 统计全年签到天数
BITCOUNT user:1001:sign:2024
# (integer) 180

# 用户在线状态
SETBIT online:20240101 1001 1  # 用户1001在线
SETBIT online:20240101 1002 1  # 用户1002在线

# 统计在线人数
BITCOUNT online:20240101
# (integer) 2

六、应用场景 #

6.1 缓存 #

bash
# 缓存用户信息
SET cache:user:1001 '{"id":1001,"name":"John","age":25}' EX 3600

# 获取缓存
GET cache:user:1001

# 缓存穿透保护
SET cache:user:9999 "NULL" EX 60

6.2 计数器 #

bash
# 文章阅读量
INCR article:1001:views

# 点赞数
INCR article:1001:likes

# 接口访问次数
INCR api:/user/info:count

# 限流计数器
SET rate:user:1001 0 EX 60
INCR rate:user:1001
GET rate:user:1001

6.3 分布式锁 #

bash
# 获取锁
SET lock:resource "uuid-12345" NX EX 30
# OK  获取成功

# 释放锁(需要Lua脚本保证原子性)
# if redis.call('get', KEYS[1]) == ARGV[1] then
#     return redis.call('del', KEYS[1])
# else
#     return 0
# end
EVAL "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end" 1 lock:resource "uuid-12345"

6.4 分布式ID #

bash
# 生成唯一ID
INCR global:next_id
# (integer) 1

INCR global:next_id
# (integer) 2

# 带日期的ID
SET order:id:20240101 0
INCR order:id:20240101
# (integer) 1
# 组合:20240101001

6.5 验证码 #

bash
# 设置验证码,5分钟过期
SET captcha:phone:13800138000 "123456" EX 300

# 验证
GET captcha:phone:13800138000
# "123456"

# 验证后删除
DEL captcha:phone:13800138000

七、性能优化 #

7.1 批量操作 #

bash
# 不推荐:多次单操作
SET key1 "value1"
SET key2 "value2"
SET key3 "value3"

# 推荐:批量操作
MSET key1 "value1" key2 "value2" key3 "value3"

# 批量获取
MGET key1 key2 key3

7.2 合理设置过期 #

bash
# 设置合理的过期时间
SET cache:user:1001 "data" EX 3600

# 避免缓存雪崩:添加随机过期时间
SET cache:user:1001 "data" EX 3600
SET cache:user:1002 "data" EX 3700
SET cache:user:1003 "data" EX 3800

7.3 内存优化 #

bash
# 使用整数
SET counter 100  # int编码,节省内存

# 避免过长的键名
# 不推荐
SET user:information:with:id:1001 "data"
# 推荐
SET u:1001 "data"

# 压缩大值
# 存储前压缩,读取后解压

八、总结 #

字符串操作命令:

命令 说明
SET 设置值
GET 获取值
MSET 批量设置
MGET 批量获取
INCR 自增
DECR 自减
APPEND 追加
STRLEN 获取长度

应用场景:

场景 实现方式
缓存 SET + EX
计数器 INCR
分布式锁 SET NX EX
分布式ID INCR
签到 SETBIT

下一步,让我们学习Redis列表List!

最后更新:2026-03-27