如今信息量井喷式增长,各种各样的数据出现(用户定位数据,图片数据,音乐数据等),大数据的背景下Mysql等关系型数据库(RDBMS)无法满足大量数据要求。因此,出现了很多新型的非关系型数据,Nosql数据库就能轻松解决这些问题,专门存储大型文件、图片、博客。目前一个基本的互联网项目:
为什么要用NoSQL?
方便扩展(数据之间没有关系,很好扩展!)
大数据量高性能(Redis一秒可以写8万次,读11万次,NoSQL的缓存记录级,是一种细粒度的缓存,性能会比较高!)
数据类型是多样型的!(不需要事先设计数据库,随取随用)
传统的 RDBMS 和 NoSQL:
RDBMS(关系型数据库)
- 结构化组织
- SQL
- 数据和关系都存在单独的表中 row col
- 操作,数据定义语言
- 严格的一致性
- 基础的事务
- ...
NoSQL(非关系型数据库)
- 不仅仅是数据
- 没有固定的查询语言
- 键值对存储,列存储,文档存储,图形数据库(社交关系)
- 最终一致性
- CAP定理和BASE理论
- 高性能,高可用,高可扩展
- ...
了解:3V + 3高
高并发
高可扩展
高性能
真正在公司中的实践:NoSQL + RDBMS 一起使用才是最强的。
推荐阅读:阿里云的这群疯子(https://yq.aliyun.com/articles/653511)
阿里巴巴架构发展历程
数据层架构
# 商品信息:名称、价格、商家信息
- 一般存放在关系型数据库:MySQL,阿里巴巴使用的MySQL都是经过内部改动的(王坚)
# 商品描述、评论(文字居多)
- 文档型数据库:MongoDB
# 图片
- 分布式文件系统 FastDFS
- 淘宝:TFS
- Google: GFS
- Hadoop: HDFS
- 阿里云: oss
# 商品关键字,用于搜索
- 搜索引擎:solr elasticsearch
- 阿里:Isearch(多隆)
# 商品热门的波段信息
- 内存数据库:Redis Tair Memcache
# 商品交易,外部支付接口
- 第三方应用
KV键值对
文档型数据库(bson数据格式):
列存储数据库
图关系数据库
用于广告推荐,社交网络
Neo4j、InfoGrid
四者对比
分类 | Examples举例 | 典型应用场景 | 数据模型 | 优点 | 缺点 |
---|---|---|---|---|---|
键值对(key-value) | Tokyo Cabinet/Tyrant, Redis, Voldemort, Oracle BDB | 内容缓存,主要用于处理大量数据的高访问负载,也用于一些日志系统等等。 | Key 指向 Value 的键值对,通常用hash table来实现 | 查找速度快 | 数据无结构化,通常只被当作字符串或者二进制数据 |
列存储数据库 | Cassandra, HBase, Riak | 分布式的文件系统 | 以列簇式存储,将同一列数据存在一起 | 查找速度快,可扩展性强,更容易进行分布式扩展 | 功能相对局限 |
文档型数据库 | CouchDB, MongoDb | Web应用(与Key-Value类似,Value是结构化的,不同的是数据库能够了解Value的内容) | Key-Value对应的键值对,Value为结构化数据 | 数据结构要求不严格,表结构可变,不需要像关系型数据库一样需要预先定义表结构 | 查询性能不高,而且缺乏统一的查询语法。 |
图形(Graph)数据库 | Neo4J, InfoGrid, Infinite Graph | 社交网络,推荐系统等。专注于构建关系图谱 | 图结构 | 利用图结构相关算法。比如最短路径寻址,N度关系查找等 | 很多时候需要对整个图做计算才能得出需要的信息,而且这种结构不太好做分布式的集群 |
使用宝塔面板安装Redis,安装路径:/www/server/redis/
将redis的配置文件复制到程序安装目录 /usr/local/bin/myconfig
下
redis默认不是后台启动的,需要修改配置文件!
启动redis服务,并使用redis-cli连接指定的端口号测试(Redis的默认端口6379)
[root src]# ./redis-server &
[root src]# ping
127.0.0.1:6379> ping
查看redis服务是否启动,关闭Redis服务,再次查看进程是否存在
[root src]# ps -ef|grep redis
[root src]# redis-cli
127.0.0.1:6379> shutdown
127.0.0.1:6379> quit / exit
后续会使用单机多Redis启动集群测试!
**redis-benchmark:**压力测试工具,Redis官方提供的性能测试工具,参数选项如下:
简单测试:
# 测试:100个并发连接 100000请求
redis-benchmark -h 127.0.0.1 -p 6379 -c 100 -n 100000
测试结果(片段):
====== SET ======
100000 requests completed in 1.22 seconds
100 parallel clients
3 bytes payload
keep alive: 1
host configuration "save": 3600 1 300 100 60 10000
host configuration "appendonly": no
multi-thread: no
Latency by percentile distribution:
0.000% <= 0.199 milliseconds (cumulative count 1)
50.000% <= 0.591 milliseconds (cumulative count 51183)
75.000% <= 0.711 milliseconds (cumulative count 75554)
87.500% <= 0.839 milliseconds (cumulative count 88224)
93.750% <= 0.903 milliseconds (cumulative count 94145)
96.875% <= 1.071 milliseconds (cumulative count 96925)
98.438% <= 1.383 milliseconds (cumulative count 98441)
99.219% <= 1.839 milliseconds (cumulative count 99228)
99.609% <= 2.271 milliseconds (cumulative count 99614)
99.805% <= 2.551 milliseconds (cumulative count 99805)
99.902% <= 2.815 milliseconds (cumulative count 99903)
99.951% <= 2.975 milliseconds (cumulative count 99954)
99.976% <= 3.071 milliseconds (cumulative count 99977)
99.988% <= 3.159 milliseconds (cumulative count 99988)
99.994% <= 3.231 milliseconds (cumulative count 99994)
99.997% <= 3.295 milliseconds (cumulative count 99997)
99.998% <= 3.335 milliseconds (cumulative count 99999)
99.999% <= 3.343 milliseconds (cumulative count 100000)
100.000% <= 3.343 milliseconds (cumulative count 100000)
Cumulative distribution of latencies:
0.000% <= 0.103 milliseconds (cumulative count 0)
0.002% <= 0.207 milliseconds (cumulative count 2)
0.035% <= 0.303 milliseconds (cumulative count 35)
0.227% <= 0.407 milliseconds (cumulative count 227)
7.376% <= 0.503 milliseconds (cumulative count 7376)
57.797% <= 0.607 milliseconds (cumulative count 57797)
74.875% <= 0.703 milliseconds (cumulative count 74875)
84.250% <= 0.807 milliseconds (cumulative count 84250)
94.145% <= 0.903 milliseconds (cumulative count 94145)
96.346% <= 1.007 milliseconds (cumulative count 96346)
97.140% <= 1.103 milliseconds (cumulative count 97140)
97.705% <= 1.207 milliseconds (cumulative count 97705)
98.150% <= 1.303 milliseconds (cumulative count 98150)
98.507% <= 1.407 milliseconds (cumulative count 98507)
98.708% <= 1.503 milliseconds (cumulative count 98708)
98.891% <= 1.607 milliseconds (cumulative count 98891)
99.026% <= 1.703 milliseconds (cumulative count 99026)
99.178% <= 1.807 milliseconds (cumulative count 99178)
99.303% <= 1.903 milliseconds (cumulative count 99303)
99.396% <= 2.007 milliseconds (cumulative count 99396)
99.486% <= 2.103 milliseconds (cumulative count 99486)
99.982% <= 3.103 milliseconds (cumulative count 99982)
100.000% <= 4.103 milliseconds (cumulative count 100000)
Summary:
throughput summary: 81833.06 requests per second
latency summary (msec):
avg min p50 p95 p99 max
0.658 0.192 0.591 0.927 1.687 3.343
redis默认有16个数据库,默认使用的第0个;16个数据库为:DB 0 ~ DB 15,默认使用DB 0 ,可以使用 select n
切换到DB n。
[root@VM-4-12-centos ~]# cd /www/server/redis/src
[root@VM-4-12-centos src]# ./redis-cli
127.0.0.1:6379> config get databases # 命令行查看数据库数量databases
1) "databases"
2) "16"
127.0.0.1:6379> select 6 # 切换数据库 DB6
OK
127.0.0.1:6379[6]> dbsize # 查看当前数据库的大小,size与key数量相关
(integer) 0
127.0.0.1:6379[6]> set name cwlin
OK
127.0.0.1:6379[6]> dbsize
(integer) 1
127.0.0.1:6379[6]> select 1 # 不同数据库之间数据是不能互通的,并且dbsize 是根据库中key的个数
OK
127.0.0.1:6379[1]> get name # db1中并不能获取db6中的键值对
(nil)
127.0.0.1:6379[1]> dbsize
(integer) 0
127.0.0.1:6379[1]> select 6
OK
127.0.0.1:6379[6]> get name
"cwlin"
127.0.0.1:6379[6]> dbsize
(integer) 1
127.0.0.1:6379[6]> keys * # 查看当前数据库中所有的key
1) "name"
127.0.0.1:6379[6]> flushdb # 清空当前数据库中的键值对
OK
127.0.0.1:6379[6]> flushall # 清空所有数据库的键值对
OK
Redis是单线程的,Redis是基于内存操作的。
Redis为什么单线程速度还这么快,性能这么高呢?
在redis中无论什么数据类型,在数据库中都是以key-value形式保存,通过进行对Redis-key的操作,来完成对数据库中数据的操作。
常用命令如下:
exists key
:判断键是否存在move key db
:将键值对移动到指定数据库del key
:删除键值对expire key second
:设置键值对的过期时间ttl key
: 查看key的过期剩余时间type key
:查看value的数据类型Linux 操作:
127.0.0.1:6379> flushall # 清空所有键值对
OK
127.0.0.1:6379> set name cwlin
OK
127.0.0.1:6379> set age 24
OK
127.0.0.1:6379> exists name # 判断键是否存在
(integer) 1 # 存在
127.0.0.1:6379> exists gender
(integer) 0 # 不存在
127.0.0.1:6379> move name 1 # 将键值对移动到指定数据库 DB1
(integer) 1
127.0.0.1:6379> keys *
1) "age"
127.0.0.1:6379> expire age 10 # 设置键值对的过期时间
(integer) 1 # 设置成功,开始计数
127.0.0.1:6379> keys *
1) "age"
127.0.0.1:6379> ttl age
(integer) 5
127.0.0.1:6379> keys * # 过期的key会被自动delete
(empty array)
127.0.0.1:6379> ttl age # 查看key的过期剩余时间
(integer) -2 # -2表示key过期,-1表示key未设置过期时间
127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> keys *
1) "name"
127.0.0.1:6379[1]> del name # 删除键值对
(integer) 1 # 删除个数
127.0.0.1:6379> type name # 查看value的数据类型
string
127.0.0.1:6379> type age
string
关于TTL
命令:Redis的key,通过TTL命令返回key的过期时间,一般来说有3种:
关于重命名RENAME
和RENAMENX
RENAME key newkey
:修改 key 的名称RENAMENX key newkey
:仅当 newkey 不存在时,将 key 改名为 newkey 。更多命令详见官网:
命令 | 描述 | 示例 |
---|---|---|
APPEND key value |
向指定的key的value后追加字符串 | 127.0.0.1:6379> set msg hello OK 127.0.0.1:6379> append msg " world" (integer) 11 127.0.0.1:6379> get msg “hello world” |
DECR/INCR key |
将指定key的value数值进行+1/-1(仅对于数字) | 127.0.0.1:6379> set age 20 OK 127.0.0.1:6379> incr age (integer) 21 127.0.0.1:6379> decr age (integer) 20 |
INCRBY/DECRBY key n |
按指定的步长对数值进行加减 | 127.0.0.1:6379> INCRBY age 5 (integer) 25 127.0.0.1:6379> DECRBY age 10 (integer) 15 |
INCRBYFLOAT key n |
为数值加上浮点型数值 | 127.0.0.1:6379> INCRBYFLOAT age 5.2 “20.2” |
STRLEN key |
获取key保存值的字符串长度 | 127.0.0.1:6379> get msg “hello world” 127.0.0.1:6379> STRLEN msg (integer) 11 |
GETRANGE key start end |
按起止位置获取字符串(闭区间,起止位置都取) | 127.0.0.1:6379> get msg “hello world” 127.0.0.1:6379> GETRANGE msg 3 9 “lo worl” |
SETRANGE key offset value |
用指定的value 替换key中 offset开始的值 | 127.0.0.1:6379> SETRANGE msg 2 hello (integer) 7 127.0.0.1:6379> get msg “tehello” |
GETSET key value |
将给定 key 的值设为 value ,并返回 key 的旧值(old value)。 | 127.0.0.1:6379> GETSET msg test “hello world” |
SETNX key value |
仅当key不存在时进行set | 127.0.0.1:6379> SETNX msg test (integer) 0 127.0.0.1:6379> SETNX name sakura (integer) 1 |
SETEX key seconds value |
set 键值对并设置过期时间 | 127.0.0.1:6379> setex name 10 root OK 127.0.0.1:6379> get name (nil) |
MSET key1 value1 [key2 value2..] |
批量set键值对 | 127.0.0.1:6379> MSET k1 v1 k2 v2 k3 v3 OK |
MSETNX key1 value1 [key2 value2..] |
批量设置键值对,仅当参数中所有的key都不存在时执行 | 127.0.0.1:6379> MSETNX k1 v1 k4 v4 (integer) 0 |
MGET key1 [key2..] |
批量获取多个key保存的值 | 127.0.0.1:6379> MGET k1 k2 k3 1) “v1” 2) “v2” 3) “v3” |
PSETEX key milliseconds value |
和 SETEX 命令相似,但它以毫秒为单位设置 key 的生存时间, | |
getset key value |
如果不存在值,则返回nil,如果存在值,获取原来的值,并设置新的值 |
APPEND key value
: 向指定的key的value后追加字符串
STRLEN key
: 获取key保存值的字符串长度
127.0.0.1:6379> set key value
OK
127.0.0.1:6379> get key
"value"
127.0.0.1:6379> append key xixixi
(integer) 11
127.0.0.1:6379> get key
"valuexixixi"
127.0.0.1:6379> strlen key
(integer) 11
DECR/INCR key
: 将指定key的value数值进行+1/-1(仅对于数字)
INCRBY/DECRBY key n
: 按指定的步长对数值进行加减
INCRBYFLOAT key n
: 为数值加上浮点型数值
127.0.0.1:6379> set views 0
OK
127.0.0.1:6379> get views
"0"
127.0.0.1:6379> incr views
(integer) 1
127.0.0.1:6379> incr views
(integer) 2
127.0.0.1:6379> get views
"2"
127.0.0.1:6379> decr views
(integer) 1
127.0.0.1:6379> decr views
(integer) 0
127.0.0.1:6379> get views
"0"
127.0.0.1:6379> incrby views 9
(integer) 9
127.0.0.1:6379> incrby views 9
(integer) 18
127.0.0.1:6379> decrby views 6
(integer) 12
127.0.0.1:6379> decrby views 6
(integer) 6
127.0.0.1:6379> incrbyfloat views 5.2
“11.2”
GETRANGE key start end
: 按起止位置获取字符串(闭区间,起止位置都取)
SETRANGE key offset value
:用指定的value 替换key中 offset开始的值
127.0.0.1:6379> set msg hello,world
OK
127.0.0.1:6379> getrange msg 0 3
"hell"
127.0.0.1:6379> getrange msg 0 -1
"hello,world"
127.0.0.1:6379> set msg2 abcde
OK
127.0.0.1:6379> get msg2
"abcde"
127.0.0.1:6379> setrange msg2 2 xx
(integer) 5
127.0.0.1:6379> get msg2
"abxxe"
SETEX key seconds value
: set 键值对并设置过期时间
SETNX key value
: 仅当key不存在时进行set
PSETEX key milliseconds value
: 和 SETEX 命令相似,但它以毫秒为单位设置 key 的生存时间
127.0.0.1:6379> setex age 20 25 # 20秒后过期
OK
127.0.0.1:6379> ttl age
(integer) 17
127.0.0.1:6379> get age
"25"
127.0.0.1:6379> setnx myage 24
(integer) 1
127.0.0.1:6379> keys *
1) "msg2"
2) "myage"
3) "msg"
127.0.0.1:6379> setnx myage 30
(integer) 0
127.0.0.1:6379> get myage
"24"
127.0.0.1:6379> psetex age 5000 25
OK
127.0.0.1:6379> ttl age
(integer) 4
127.0.0.1:6379> ttl age
(integer) -2
MSET key1 value1 [key2 value2..]
: 批量set键值对
MGET key1 [key2..]
: 批量获取多个key保存的值
MSETNX key1 value1 [key2 value2..]
: 批量设置键值对,仅当参数中所有的key都不存在时执行
127.0.0.1:6379> MSET k1 v1 k2 v2 k3 v3
OK
127.0.0.1:6379> MGET k1 k2 k3
1) "v1"
2) "v2"
3) "v3"
127.0.0.1:6379> MSETNX k1 v1 k4 v4
(integer) 0 # 执行失败,因为MSETNX是原子性操作,要么一起成功,要么一起失败
127.0.0.1:6379> get k4
(nil)
GETSET key value
: 将给定 key 的值设为 value ,并返回 key 的旧值(old value)
127.0.0.1:6379> set name cwlin
OK
127.0.0.1:6379> getset name lcw
"cwlin"
127.0.0.1:6379> get name
"lcw"
127.0.0.1:6379> getset nickname chwlyn # 如果不存在旧值,则返回nil
(nil)
127.0.0.1:6379> get nickname
"chwlyn"
存入一个 user 对象
127.0.0.1:6379> set user:1 {name:cwlin,age:18}
OK
127.0.0.1:6379> get user:1
"{name:cwlin,age:18}"
127.0.0.1:6379> mset user:2:name lcw user:2:age 24
OK
127.0.0.1:6379> mget user:2:name user:2:age
1) "lcw"
2) "24"
String类似的使用场景:(value除了是字符串还可以是数字)
Redis列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边)
所有的 List 命令都是 L / R 开头的,List是可以进行双端操作的,所以命令分为LXXX和RXXX两类,有时候L也表示List,例如LLEN
LPUSH/RPUSH key value1[value2..]
: 从左边/右边向列表中PUSH值(一个或者多个)。LRANGE key start end
: 获取list 起止元素==(索引从左往右 递增)==LPUSHX/RPUSHX key value
: 向已存在的列名中push值(一个或者多个)LINSERT key BEFORE|AFTER pivot value
: 在指定列表元素的前/后 插入valueLLEN key
: 查看列表长度LINDEX key index
: 通过索引获取列表元素LSET key index value
: 通过索引为元素设值LPOP/RPOP key
: 从最左边/最右边移除值 并返回RPOPLPUSH source destination
: 将列表的尾部(右)最后一个值弹出,并返回,然后加到另一个列表的头部LTRIM key start end
: 通过下标截取指定范围内的列表LREM key count value
: List中是允许value重复的,count > 0:从头部开始搜索,然后删除指定的value至多删除count个;count < 0:从尾部开始搜索,…;count = 0:删除列表中所有的指定value。BLPOP/BRPOP key1[key2] timeout
: 移出并获取列表的第一个/最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。BRPOPLPUSH source destination timeout
: 和RPOPLPUSH功能相同,如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。Linux 操作实例:
---------------------------LPUSH---RPUSH---LRANGE--------------------------------
127.0.0.1:6379> LPUSH mylist k1 # LPUSH mylist => {1}
(integer) 1
127.0.0.1:6379> LPUSH mylist k2 # LPUSH mylist => {2,1}
(integer) 2
127.0.0.1:6379> RPUSH mylist k3 # RPUSH mylist => {2,1,3}
(integer) 3
127.0.0.1:6379> get mylist # 普通的get是无法获取list值的
(error) WRONGTYPE Operation against a key holding the wrong kind of value
127.0.0.1:6379> LRANGE mylist 0 4 # LRANGE获取起止位置范围内的元素
1) "k2"
2) "k1"
3) "k3"
127.0.0.1:6379> LRANGE mylist 0 2
1) "k2"
2) "k1"
3) "k3"
127.0.0.1:6379> LRANGE mylist 0 1
1) "k2"
2) "k1"
127.0.0.1:6379> LRANGE mylist 0 -1 # 获取全部元素
1) "k2"
2) "k1"
3) "k3"
---------------------------LPUSHX---RPUSHX-----------------------------------
127.0.0.1:6379> LPUSHX list v1 # list不存在,LPUSHX失败
(integer) 0
127.0.0.1:6379> LPUSHX list v1 v2
(integer) 0
127.0.0.1:6379> LPUSHX mylist k4 k5 # 向mylist的左边 PUSH k4 k5
(integer) 5
127.0.0.1:6379> LRANGE mylist 0 -1
1) "k5"
2) "k4"
3) "k2"
4) "k1"
5) "k3"
---------------------------LINSERT---LLEN---LINDEX---LSET----------------------------
127.0.0.1:6379> LINSERT mylist after k2 ins_key1 # 在k2元素后,插入ins_key1
(integer) 6
127.0.0.1:6379> LRANGE mylist 0 -1
1) "k5"
2) "k4"
3) "k2"
4) "ins_key1"
5) "k1"
6) "k3"
127.0.0.1:6379> LLEN mylist # 查看mylist的长度
(integer) 6
127.0.0.1:6379> LINDEX mylist 3 # 获取下标为3的元素
"ins_key1"
127.0.0.1:6379> LINDEX mylist 0
"k5"
127.0.0.1:6379> LSET mylist 3 k6 # 将下标3的元素set值为k6
OK
127.0.0.1:6379> LRANGE mylist 0 -1
1) "k5"
2) "k4"
3) "k2"
4) "k6"
5) "k1"
6) "k3"
---------------------------LPOP---RPOP--------------------------
127.0.0.1:6379> LPOP mylist # 左侧(头部)弹出
"k5"
127.0.0.1:6379> RPOP mylist # 右侧(尾部)弹出
"k3"
---------------------------RPOPLPUSH--------------------------
127.0.0.1:6379> LRANGE mylist 0 -1
1) "k4"
2) "k2"
3) "k6"
4) "k1"
127.0.0.1:6379> RPOPLPUSH mylist newlist # 将mylist的最后一个值(k1)弹出,加入到newlist的头部
"k1"
127.0.0.1:6379> LRANGE newlist 0 -1
1) "k1"
127.0.0.1:6379> LRANGE mylist 0 -1
1) "k4"
2) "k2"
3) "k6"
---------------------------LTRIM--------------------------
127.0.0.1:6379> LTRIM mylist 0 1 # 截取mylist中的 0~1 部分
OK
127.0.0.1:6379> LRANGE mylist 0 -1
1) "k4"
2) "k2"
# 初始 mylist: k2,k2,k2,k2,k2,k2,k4,k2,k2,k2,k2
---------------------------LREM--------------------------
127.0.0.1:6379> LREM mylist 3 k2 # 从头部开始搜索,至多删除3个 k2
(integer) 3
# 删除后:mylist: k2,k2,k2,k4,k2,k2,k2,k2
127.0.0.1:6379> LREM mylist -2 k2 #从尾部开始搜索,至多删除2个 k2
(integer) 2
# 删除后:mylist: k2,k2,k2,k4,k2,k2
阻塞队列的应用:
BLPOP/BRPOP key1[key2] timout
: 移出并获取列表的第一个/最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。BRPOPLPUSH source destination timeout
: 和RPOPLPUSH功能相同,如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。---------------------------BLPOP---BRPOP--------------------------
127.0.0.1:6379> lpush mylist k2 k2 k2 k4 k2 k2
(integer) 6
127.0.0.1:6379> lpush newlist k1 k3
(integer) 2
127.0.0.1:6379> LRANGE mylist 0 -1
1) "k2"
2) "k2"
3) "k4"
4) "k2"
5) "k2"
6) "k2"
127.0.0.1:6379> LRANGE newlist 0 -1
1) "k3"
2) "k1"
127.0.0.1:6379> blpop newlist mylist 30 # 从newlist中弹出第一个值,mylist作为候选
1) "newlist" # 从newlist弹出
2) "k3"
127.0.0.1:6379> blpop newlist mylist 30
1) "newlist" # 从newlist弹出
2) "k1"
127.0.0.1:6379> blpop newlist mylist 30
1) "mylist" # 由于newlist空了 从mylist中弹出
2) "k2"
127.0.0.1:6379> blpop newlist 30
(30.10s) # 阻塞超时
127.0.0.1:6379> blpop newlist 30
# 阻塞等待
127.0.0.1:6379> lpush newlist test # 通过连接另一个客户端,向newlist中push test
(integer) 1
127.0.0.1:6379> blpop newlist 30 # 此时阻塞被解决
1) "newlist"
2) "test"
(2.70s)
小结:
list实际上是一个链表,before Node after, left, right 都可以插入值
如果key不存在,则创建新的链表;如果key存在,新增内容
如果移除了所有值,则为空链表,即不存在
在两边插入或者改动值,效率最高!修改中间元素,效率相对较低。
应用:消息排队!
Redis的Set是string类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。
Set 相关的操作都是 S 开头,常用命令如下:
SADD key member1[member2..]
: 向集合中无序增加一个/多个成员SCARD key
: 获取集合的成员数SMEMBERS key
: 返回集合中所有的成员SISMEMBER key member
: 查询member元素是否是集合的成员,结果是无序的SRANDMEMBER key [count]
: 随机返回集合中count个成员,count缺省值为1SPOP key [count]
: 随机移除并返回集合中count个成员,count缺省值为1SMOVE source destination member
: 将source集合的成员member移动到destination集合SREM key member1[member2..]
: 移除集合中一个/多个成员SDIFF key1[key2..]
: 返回所有集合的差集(key1 - key2 - …)SDIFFSTORE destination key1[key2..]
: 在SDIFF的基础上,存储结果覆盖到集合中。(不能保存到其他类型key!)SINTER key1 [key2..]
: 返回所有集合的交集(key1 ∩ key2 ∩ …)SINTERSTORE destination key1[key2..]
: 在SINTER的基础上,存储结果覆盖到集合中。(不能保存到其他类型key!)SUNION key1 [key2..]
: 返回所有集合的并集(key1 ∪ key2 ∪ …)SUNIONSTORE destination key1 [key2..]
: 在SUNION的基础上,存储结果覆盖到集合中。(不能保存到其他类型key!)SSCAN KEY [MATCH pattern] [COUNT count]
: 在大量数据环境下,使用此命令遍历集合中元素,每次遍历count个。Linux 操作实例:
---------------SADD--SCARD--SMEMBERS--SISMEMBER--------------------
127.0.0.1:6379> SADD myset m1 m2 m3 m4 # 向myset中增加成员 m1~m4
(integer) 4
127.0.0.1:6379> SCARD myset # 获取集合的成员数目
(integer) 4
127.0.0.1:6379> smembers myset # 获取集合中所有成员
1) "m4"
2) "m3"
3) "m2"
4) "m1"
127.0.0.1:6379> SISMEMBER myset m5 # 查询m5是否是myset的成员
(integer) 0 # 不是,返回0
127.0.0.1:6379> SISMEMBER myset m2
(integer) 1 # 是,返回1
127.0.0.1:6379> SISMEMBER myset m3
(integer) 1
---------------------SRANDMEMBER--SPOP----------------------------------
127.0.0.1:6379> SRANDMEMBER myset 3 # 随机返回3个成员
1) "m2"
2) "m3"
3) "m4"
127.0.0.1:6379> SRANDMEMBER myset # 随机返回1个成员
"m3"
127.0.0.1:6379> SPOP myset 2 # 随机移除并返回2个成员
1) "m1"
2) "m4"
# 将set还原到{m1,m2,m3,m4}
---------------------SMOVE--SREM----------------------------------------
127.0.0.1:6379> SMOVE myset newset m3 # 将myset中m3成员移动到newset集合
(integer) 1
127.0.0.1:6379> SMEMBERS myset
1) "m4"
2) "m2"
3) "m1"
127.0.0.1:6379> SMEMBERS newset
1) "m3"
127.0.0.1:6379> SREM newset m3 # 从newset中移除m3元素
(integer) 1
127.0.0.1:6379> SMEMBERS newset
(empty list or set)
# 下面开始是多集合操作,多集合操作中若只有一个参数默认和自身进行运算
# setx => {m1,m2,m4,m6}, sety => {m2,m5,m6}, setz => {m1,m3,m6}
-----------------------------SDIFF------------------------------------
127.0.0.1:6379> SDIFF setx sety setz # 等价于 setx - sety - setz
1) "m4"
127.0.0.1:6379> SDIFF setx sety # setx - sety
1) "m4"
2) "m1"
127.0.0.1:6379> SDIFF sety setx # sety - setx
1) "m5"
-------------------------SINTER---------------------------------------
127.0.0.1:6379> SINTER setx sety setz # 求 setx、sety、setx 的交集
1) "m6"
127.0.0.1:6379> SINTER setx sety # 求setx sety 的交集
1) "m2"
2) "m6"
-------------------------SUNION---------------------------------------
127.0.0.1:6379> SUNION setx sety setz # setx sety setz 的并集
1) "m4"
2) "m6"
3) "m3"
4) "m2"
5) "m1"
6) "m5"
127.0.0.1:6379> SUNION setx sety # setx sety 的并集
1) "m4"
2) "m6"
3) "m2"
4) "m1"
5) "m5"
-------------------------SSCAN----------------------------------------
127.0.0.1:6379> sadd myset cwlin lcw coder_lcw chwlyn
(integer) 4
127.0.0.1:6379> sscan myset 0 match chw
1) "0"
2) (empty array)
127.0.0.1:6379> sscan myset 0 match *lcw*
1) "0"
2) 1) "coder_lcw"
2) "lcw"
127.0.0.1:6379> sscan myset 0 match *cw*
1) "0"
2) 1) "coder_lcw"
2) "cwlin"
3) "lcw"
127.0.0.1:6379> sscan myset 0 match *chw*
1) "0"
2) 1) "chwlyn"
应用:微博等网站的关注用户,QQ、微信的好友都可以放在一个集合中
Redis hash 是一个string类型的field和value的映射表,hash特别适合用于存储对象。
类似 Map 集合 —— key = {key = value},Hash 的相关操作都以 H 开头,常见命令如下:
HSET key field value
: 将哈希表 key 中的字段 field 的值设为 value 。重复设置同一个field会覆盖,返回0HMSET key field1 value1 [field2 value2..]
: 同时将多个 field-value (域-值)对设置到哈希表 key 中。HSETNX key field value
: 只有在字段 field 不存在时,设置哈希表字段的值。HEXISTS key field
: 查看哈希表 key 中,指定的字段是否存在。HGET key field value
: 获取存储在哈希表中指定字段的值HMGET key field1 [field2..]
: 获取所有给定字段的值HGETALL key
: 获取在哈希表key 的所有字段和值HKEYS key
: 获取哈希表key中所有的字段HLEN key
: 获取哈希表中字段的数量HVALS key
: 获取哈希表中所有值HDEL key field1 [field2..]
: 删除哈希表key中一个/多个field字段HINCRBY key field n
: 为哈希表 key 中的指定字段的整数值加上增量n,并返回增量后结果 一样只适用于整数型字段HINCRBYFLOAT key field n
: 为哈希表 key 中的指定字段的浮点数值加上增量 n。HSCAN key cursor [MATCH pattern] [COUNT count]
: 迭代哈希表中的键值对。Linux 操作实例:
------------------------HSET--HMSET--HSETNX----------------
127.0.0.1:6379> HSET studentx name lcw # 将studentx哈希表作为一个对象,设置name为sakura
(integer) 1
127.0.0.1:6379> HSET studentx name cwlin # 重复设置field进行覆盖,并返回0
(integer) 0
127.0.0.1:6379> HSET studentx age 24 # 设置studentx的age为20
(integer) 1
127.0.0.1:6379> HMSET studentx sex 1 tel 12345678901 # 设置sex为1,tel为15623667886
OK
127.0.0.1:6379> HSETNX studentx name cwlin # HSETNX 设置已存在的field
(integer) 0 # 失败
127.0.0.1:6379> HSETNX studentx email [email protected]
(integer) 1 # 成功
----------------------HEXISTS--------------------------------
127.0.0.1:6379> HEXISTS studentx name # name字段在studentx中是否存在
(integer) 1 # 存在
127.0.0.1:6379> HEXISTS studentx addr
(integer) 0 # 不存在
-------------------HGET--HMGET--HGETALL-----------
127.0.0.1:6379> HGET studentx name # 获取studentx中name字段的value
"cwlin"
127.0.0.1:6379> HMGET studentx name age tel # 获取studentx中name、age、tel字段的value
1) "cwlin"
2) "24"
3) "12345678901"
127.0.0.1:6379> HGETALL studentx # 获取studentx中所有的field及其value
1) "name"
2) "cwlin"
3) "age"
4) "24"
5) "sex"
6) "1"
7) "tel"
8) "12345678901"
9) "email"
10) "[email protected]"
--------------------HKEYS--HLEN--HVALS--------------
127.0.0.1:6379> HKEYS studentx # 查看studentx中所有的field
1) "name"
2) "age"
3) "sex"
4) "tel"
5) "email"
127.0.0.1:6379> HLEN studentx # 查看studentx中的字段数量
(integer) 5
127.0.0.1:6379> HVALS studentx # 查看studentx中所有的value
1) "cwlin"
2) "24"
3) "1"
4) "12345678901"
5) "[email protected]"
-------------------------HDEL--------------------------
127.0.0.1:6379> HDEL studentx sex tel # 删除studentx 中的sex、tel字段
(integer) 2
127.0.0.1:6379> HKEYS studentx
1) "name"
2) "age"
3) "email"
-------------HINCRBY--HINCRBYFLOAT------------------------
127.0.0.1:6379> HINCRBY studentx age 1 # studentx的age字段数值+1
(integer) 25
127.0.0.1:6379> HINCRBY studentx name 1 # 非整数字型字段不可用
(error) ERR hash value is not an integer
127.0.0.1:6379> HINCRBYFLOAT studentx weight 0.6 # weight字段增加0.6
"65.8"
应用:Hash 用来存放经常变更数据、对象信息,尤其是用户信息之类的,经常变动的信息!
不同的是每个元素都会关联一个double类型的分数(score)。redis正是通过分数来为集合中的成员进行从小到大的排序。
在插入时,可以增加一个 score 来进行分组排序,ZSet 的相关操作都是 Z 开头,常见命令如下:
ZADD key score member1 [score2 member2]
: 向有序集合添加一个或多个成员,或者更新已存在成员的分数
ZADD 【key】 [ NX|XX ] [ CH ] [ INCR ] score member [score member …]
ZCARD key
: 获取有序集合的成员数ZCOUNT key min max
: 计算在有序集合中指定区间score的成员数ZINCRBY key n member
: 有序集合中对指定成员的分数加上增量 nZSCORE key member
: 返回有序集中,成员的分数值ZRANK key member
: 返回有序集合中指定成员的索引ZRANGE key start end [withscores]
: 通过索引区间返回有序集合成指定区间内的成员(升序,下同)
ZRANGEBYLEX key min max
: 通过字典区间返回有序集合的成员ZRANGEBYSCORE key min max [withscores]
: 通过分数返回有序集合指定区间内的成员,-inf 和 +inf分别表示最小最大值,只支持开区间()ZLEXCOUNT key min max
: 在有序集合中计算指定字典区间内成员数量ZREM key member1 [member2..]
: 移除有序集合中一个/多个成员ZREMRANGEBYLEX key min max
: 移除有序集合中给定的字典区间的所有成员ZREMRANGEBYRANK key start stop
: 移除有序集合中给定的排名区间的所有成员ZREMRANGEBYSCORE key min max
: 移除有序集合中给定的分数区间的所有成员ZREVRANGE key start end [withscores]
: 返回有序集中指定区间内的成员,通过索引,分数从高到底(降序,下同)ZREVRANGEBYSCORRE key max min
: 返回有序集中指定分数区间内的成员,分数从高到低排序ZREVRANGEBYLEX key max min
: 返回有序集中指定字典区间内的成员,按字典顺序倒序ZREVRANK key member
: 返回有序集合中指定成员的排名,有序集成员按分数值递减(从大到小)排序ZINTERSTORE destination numkeys key1 [key2 ..]
: 计算给定的一个或多个有序集的交集并将结果集存储在新的有序集合 key 中,numkeys:表示参与运算的集合数,将score相加作为结果的scoreZUNIONSTORE destination numkeys key1 [key2..]
: 计算给定的一个或多个有序集的交集并将结果集存储在新的有序集合 key 中ZSCAN key cursor [MATCH pattern\] [COUNT count]
: 迭代有序集合中的元素(包括元素成员和元素分值)Linux 操作实例:
-------------------ZADD--ZCARD--ZCOUNT--------------
127.0.0.1:6379> ZADD myzset 1 m1 2 m2 3 m3 # 向有序集合myzset中添加成员m1 score=1 以及成员m2 score=2..
(integer) 2
127.0.0.1:6379> ZCARD myzset # 获取有序集合的成员数
(integer) 2
127.0.0.1:6379> ZCOUNT myzset 0 1 # 获取score在 [0,1]区间的成员数量
(integer) 1
127.0.0.1:6379> ZCOUNT myzset 0 2
(integer) 2
----------------ZINCRBY--ZSCORE--------------------------
127.0.0.1:6379> ZINCRBY myzset 5 m2 # 将成员m2的score +5
"7"
127.0.0.1:6379> ZSCORE myzset m1 # 获取成员m1的score
"1"
127.0.0.1:6379> ZSCORE myzset m2
"7"
--------------ZRANK--ZRANGE-----------------------------------
127.0.0.1:6379> ZRANK myzset m1 # 获取成员m1的索引,索引按照score排序,score相同索引值按字典顺序顺序增加
(integer) 0
127.0.0.1:6379> ZRANK myzset m2
(integer) 2
127.0.0.1:6379> ZRANGE myzset 0 1 # 获取索引在0~1的成员
1) "m1"
2) "m3"
127.0.0.1:6379> ZRANGE myzset 0 -1 # 获取全部成员
1) "m1"
2) "m3"
3) "m2"
# testset=>{abc,add,amaze,apple,back,java,redis} score均为0
------------------ZRANGEBYLEX---------------------------------
127.0.0.1:6379> ZRANGEBYLEX testset - + # 返回所有成员
1) "abc"
2) "add"
3) "amaze"
4) "apple"
5) "back"
6) "java"
7) "redis"
127.0.0.1:6379> ZRANGEBYLEX testset - + LIMIT 0 3 # 分页,按索引显示查询结果的 0,1,2 条记录
1) "abc"
2) "add"
3) "amaze"
127.0.0.1:6379> ZRANGEBYLEX testset - + LIMIT 3 3 # 显示 3,4,5 条记录
1) "apple"
2) "back"
3) "java"
127.0.0.1:6379> ZRANGEBYLEX testset (- [apple # 显示 (-,apple] 区间内的成员
1) "abc"
2) "add"
3) "amaze"
4) "apple"
127.0.0.1:6379> ZRANGEBYLEX testset [apple [java # 显示 [apple,java]字典区间的成员
1) "apple"
2) "back"
3) "java"
-----------------------ZRANGEBYSCORE---------------------
127.0.0.1:6379> ZRANGEBYSCORE myzset 1 10 # 返回score在 [1,10]之间的的成员
1) "m1"
2) "m3"
3) "m2"
127.0.0.1:6379> ZRANGEBYSCORE myzset 1 5
1) "m1"
2) "m3"
--------------------ZLEXCOUNT-----------------------------
127.0.0.1:6379> ZLEXCOUNT testset - +
(integer) 7
127.0.0.1:6379> ZLEXCOUNT testset [apple [java
(integer) 3
------------------ZREM--ZREMRANGEBYLEX--ZREMRANGBYRANK--ZREMRANGEBYSCORE--------------------------------
127.0.0.1:6379> ZREM testset abc # 移除成员abc
(integer) 1
127.0.0.1:6379> ZREMRANGEBYLEX testset [apple [java # 移除字典区间[apple,java]中的所有成员
(integer) 3
127.0.0.1:6379> ZREMRANGEBYRANK testset 0 1 # 移除排名0~1的所有成员
(integer) 2
127.0.0.1:6379> ZREMRANGEBYSCORE myzset 0 3 # 移除score在[0,3]的成员
(integer) 2
# testset => {abc,add,apple,amaze,back,java,redis} score均为0
# myzset => {(m1,1),(m2,2),(m3,3),(m4,4),(m7,7),(m9,9)}
----------------ZREVRANGE--ZREVRANGEBYSCORE--ZREVRANGEBYLEX-----------
127.0.0.1:6379> ZREVRANGE myzset 0 3 # 按score递减排序,然后按索引,返回结果的 0~3
1) "m9"
2) "m7"
3) "m4"
4) "m3"
127.0.0.1:6379> ZREVRANGE myzset 2 4 # 返回排序结果的 索引的2~4
1) "m4"
2) "m3"
3) "m2"
127.0.0.1:6379> ZREVRANGEBYSCORE myzset 6 2 # 按score递减顺序 返回集合中分数在[2,6]之间的成员
1) "m4"
2) "m3"
3) "m2"
127.0.0.1:6379> ZREVRANGEBYLEX testset [java (add # 按字典倒序 返回集合中(add,java]字典区间的成员
1) "java"
2) "back"
3) "apple"
4) "amaze"
-------------------------ZREVRANK------------------------------
127.0.0.1:6379> ZREVRANK myzset m7 # 按score递减顺序,返回成员m7索引
(integer) 1
127.0.0.1:6379> ZREVRANK myzset m2
(integer) 4
# mathscore => {(xm,90),(xh,95),(xg,87)} 小明、小红、小刚的数学成绩
# enscore => {(xm,70),(xh,93),(xg,90)} 小明、小红、小刚的英语成绩
-------------------ZINTERSTORE--ZUNIONSTORE-----------------------------------
127.0.0.1:6379> ZINTERSTORE sumscore 2 mathscore enscore # 将mathscore enscore进行合并 结果存放到sumscore
(integer) 3
127.0.0.1:6379> ZRANGE sumscore 0 -1 withscores # 合并后的score是之前集合中所有score的和
1) "xm"
2) "160"
3) "xg"
4) "177"
5) "xh"
6) "188"
127.0.0.1:6379> ZUNIONSTORE lowestscore 2 mathscore enscore AGGREGATE MIN # 取两个集合的成员score最小值作为结果的
(integer) 3
127.0.0.1:6379> ZRANGE lowestscore 0 -1 withscores
1) "xm"
2) "70"
3) "xg"
4) "87"
5) "xh"
6) "93"
应用:
官方文档 :https://www.redis.net.cn/order/3685.html
Geospatial 相关的命令都以 GEO 开头,常用命令如下:
geoadd key longitud(经度) latitude(纬度) member [..]
: 将具体经纬度的坐标存入一个有序集合
### 规则:两级无法直接添加,我们一般会下载城市数据,直接通过java程序一次性导入
127.0.0.1:6379> geoadd China:city 116.23128 40.22077 beijing
(integer) 1
127.0.0.1:6379> geoadd China:city 121.48941 31.40527 shanghai
(integer) 1
127.0.0.1:6379> geoadd China:city 106.54041 29.40268 chongqing
(integer) 1
127.0.0.1:6379> geoadd China:city 113.28063 23.12517 guangzhou 114.08594 22.5483 shenzhen
(integer) 2
geopos key member [member..]
: 获取集合中的一个/多个成员坐标
127.0.0.1:6379> geopos China:city beijing
1) 1) "116.23128265142440796"
2) "40.22076905438526495"
127.0.0.1:6379> geopos China:city shanghai
1) 1) "121.48941010236740112"
2) "31.40526993848380499"
127.0.0.1:6379> geopos China:city guangzhou shenzhen
1) 1) "113.28062742948532104"
2) "23.12516983418487371"
2) 1) "114.08593922853469849"
2) "22.54830024969439961"
geodist key member1 member2 [unit]
: 返回两个给定位置之间的距离。默认以米作为单位。
m 表示单位为米。
km 表示单位为千米。
mi 表示单位为英里。
ft 表示单位为英尺。
### 如果两个位置之间的其中一个不存在, 那么命令返回空值。
127.0.0.1:6379> geodist China:city guangzhou shenzhen
"104553.4095"
127.0.0.1:6379> geodist China:city shanghai guangzhou
"1226603.4698"
127.0.0.1:6379> geodist China:city shanghai guangzhou km
"1226.6035"
georadius key longitude latitude radius m|km|mi|ft [WITHCOORD][WITHDIST] [WITHHASH] [COUNT count] [ASC | DESC]
: 以给定的经纬度为中心, 返回集合包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。
georadius
就可以完成 附近的人功能# 查询经纬度(120,30)坐标500km半径内的成
127.0.0.1:6379> georadius China:city 120 30 500 km withcoord withdist员
1) 1) "shanghai"
2) "211.4652"
3) 1) "121.48941010236740112"
2) "31.40526993848380499"
127.0.0.1:6379> georadius China:city 120 25 1000 km withcoord withdist
1) 1) "shenzhen"
2) "660.7579"
3) 1) "114.08593922853469849"
2) "22.54830024969439961"
2) 1) "guangzhou"
2) "713.4658"
3) 1) "113.28062742948532104"
2) "23.12516983418487371"
3) 1) "shanghai"
2) "727.2109"
3) 1) "121.48941010236740112"
2) "31.40526993848380499"
127.0.0.1:6379> georadius China:city 120 25 500 km withcoord withdist
(empty array)
GEORADIUSBYMEMBER key member radius...
: 功能与GEORADIUS相同, 都可以找出位于指定范围内的元素,只是中心位置不是具体的经纬度,而是使用集合中已有的成员位置作为中心点。
### 找出指定元素周围的其他元素
127.0.0.1:6379> georadiusbymember China:city guangzhou 1000 km withcoord withdist
1) 1) "shenzhen"
2) "104.5534"
3) 1) "114.08593922853469849"
2) "22.54830024969439961"
2) 1) "guangzhou"
2) "0.0000"
3) 1) "113.28062742948532104"
2) "23.12516983418487371"
3) 1) "chongqing"
2) "968.8206"
3) 1) "106.54040783643722534"
2) "29.40268053517299762"
127.0.0.1:6379> georadiusbymember China:city beijing 500 km withcoord withdist
1) 1) "beijing"
2) "0.0000"
3) 1) "116.23128265142440796"
2) "40.22076905438526495"
geohash key member1 [member2..]
: 返回一个或多个位置的11个字符的Geohash字符串表示,使用Geohash位置52点整数编码。
geohash.org
网站使用(http://geohash.org/
)。例子:http://geohash.org/sqdtr74hyu0。### 获取指定元素经纬度坐标的geohash表示,如果两个字符串越接近,离的越近
127.0.0.1:6379> geohash China:city beijing shanghai guangzhou shenzhen
1) "wx4sucvncn0"
2) "wtw6st1uuq0"
3) "ws0e9cb3vu0"
4) "ws10k0fc750"
应用
GEO 底层的实现原理就是 Zset ,可以使用 ZSet 命令来操作 GEO
使用经纬度定位地理坐标,并用一个有序集合zset保存,所以zset命令也可以使用,具体如下:
127.0.0.1:6379> zrange China:city 0 -1 # 用 ZSet 查询所有城市(元素)
1) "chongqing"
2) "shenzhen"
3) "guangzhou"
4) "shanghai"
5) "beijing"
127.0.0.1:6379> zrem China:city chongqing # 移除一个城市(元素)
(integer) 1
127.0.0.1:6379> zrange China:city 0 -1
1) "shenzhen"
2) "guangzhou"
3) "shanghai"
4) "beijing"
官方文档 :https://www.redis.net.cn/order/3629.htmlRedis
什么是基数?
应用
关于误差
Hyperloglog 相关的命令都以 PF 开头,常用命令如下:
PFADD key element1 [elememt2..]
: 添加指定元素到 HyperLogLog中PFCOUNT key [key]
: 返回给定 HyperLogLog 的基数估算值。PFMERGE destkey sourcekey [sourcekey..]
: 将多个 HyperLogLog 合并为一个 HyperLogLogLinux 操作实例:
------------------PFADD---PFCOUNT--------------------
127.0.0.1:6379> pfadd myname cwlin lcw chwlyn coder_lcw # 添加元素到myname
(integer) 1
127.0.0.1:6379> pfcount # 估算myname的基数
(integer) 4
127.0.0.1:6379> type myname # hyperloglog底层使用String类型
string
127.0.0.1:6379> pfadd mynickname cwlin chwlyn chw- ccccccchw # 添加元素到mynickname
(integer) 1
127.0.0.1:6379> pfcount myname
(integer) 4
127.0.0.1:6379> type myname
string
-----------------------PFMERGE-----------------------
127.0.0.1:6379> pfmerge name myname mynickname # 合并 myname 和 mynickname 到 name
OK
127.0.0.1:6379> pfcount name # 估算基数
(integer) 6
使用位存储,信息状态只有 0 和 1
应用场景:两个状态的,都可以使用bitmaps存储
BitMaps 相关的命令都以 BIT 开头或结尾,常用命令如下:
setbit key offset value
: 为指定key的offset位设置值
getbit key offset
: 获取offset位的值
bitcount key [start end]
: 统计字符串被设置为1的bit数,也可以指定统计范围按字节
BITOP operation destkey key[key..]
: 对一个或多个保存二进制位的字符串 key 进行位元操作,并将结果保存到 destkey 上。
BITOP 命令支持四个按位运算:AND,OR,XOR和NOT,因此调用该命令的有效形式为:
BITOP AND destkey srckey1 srckey2 srckey3 ... srckeyN
BITOP OR destkey srckey1 srckey2 srckey3 ... srckeyN
BITOP XOR destkey srckey1 srckey2 srckey3 ... srckeyN
BITOP NOT destkey srckey
正如你可以看到,NOT 是特殊的,因为它只需要一个输入键,因为它执行比特反转,所以它只作为一元运算符有意义。
操作结果始终存储在destkey
。
BITPOS key bit [start] [end]
: 返回字符串里面第一个被设置为1或者0的bit位。
Linux 操作实例:
---------------setbit---getbit-----------------
127.0.0.1:6379> setbit sign 0 0 # 设置sign的第0位为 0
(integer) 0
127.0.0.1:6379> setbit sign 2 1 # 设置sign的第2位为 1,不设置默认是0
(integer) 0
127.0.0.1:6379> setbit sign 3 0
(integer) 0
127.0.0.1:6379> setbit sign 4 1
(integer) 0
127.0.0.1:6379> setbit sign 5 1
(integer) 0
127.0.0.1:6379> setbit sign 6 0
(integer) 0
127.0.0.1:6379> type sign
string
127.0.0.1:6379> getbit sign 4 # 获取第4位的数值
(integer) 1
127.0.0.1:6379> getbit sign 1 # 第1位未设置,默认是0
(integer) 0
127.0.0.1:6379> getbit sign 3
(integer) 0
------------------bitcount---------------------
127.0.0.1:6379> bitcount sign # 统计sign中为1的位数
(integer) 3
bitmaps的底层
参考博客:https://juejin.cn/post/6999908907791417351
Bitmap 的底层数据结构用的是 String 类型的 SDS 数据结构来保存位数组,Redis 把每个字节数组的 8 个 bit 位利用起来,每个 bit 位表示一个元素的二值状态。
为了直观展示,我们可以理解成 buf 数组的每个字节用一行表示,每一行有 8 个 bit 位,8 个格子分别表示这个字节中的 8 个 bit 位,如下图所示:
127.0.0.1:6379> set bitmaps_test abc
OK # abc对应二进制:01100001 01100010 01100011
127.0.0.1:6379> setbit bitmaps_test 6 1
(integer) 0
127.0.0.1:6379> get bitmaps_test
"cbc"
127.0.0.1:6379> setbit bitmaps_test 22 0
(integer) 1
127.0.0.1:6379> get bitmaps_test
"cba"
8 个 bit 组成一个 Byte,所以 Bitmap 会极大地节省存储空间。 这就是 Bitmap 的优势。
multi
)....
)exec
)执行事务(
exec
)
127.0.0.1:6379> multi # 开启事务
OK
127.0.0.1:6379> set k1 v1 # 命令入队
QUEUED
127.0.0.1:6379> set k2 v2 # ...
QUEUED
127.0.0.1:6379> get k1
QUEUED
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> keys *
QUEUED
127.0.0.1:6379> exec # 执行事务
1) OK
2) OK
3) "v1"
4) OK
5) 1) "k3"
2) "k2"
3) "k1"
取消事务(
discard
)
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> discard # 取消事务
OK
127.0.0.1:6379> exec
(error) ERR EXEC without MULTI # 当前未开启事务
127.0.0.1:6379> get k1 # 放弃事务后,命令并未执行
(nil)
编译时异常(代码语法错误):事务中所有的命令都不执行
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> error k1 # 这是一条语法错误命令
(error) ERR unknown command `error`, with args beginning with: `k1`, # 会报错,但是不影响后续命令入队
127.0.0.1:6379> set k3 v3
QUEUED
127.0.0.1:6379> EXEC
(error) EXECABORT Transaction discarded because of previous errors. # 执行报错
127.0.0.1:6379> get k2
(nil) # 其他命令并没有被执行
运行时异常(代码逻辑错误):错误命令抛出异常,其他命令可以正常执行 >>> 因此,不保证事务原子性!
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set k1 v1
QUEUED
127.0.0.1:6379> set k2 v2
QUEUED
127.0.0.1:6379> INCR k1 # 这条命令逻辑错误(对字符串进行增量)
QUEUED
127.0.0.1:6379> get k1
QUEUED
127.0.0.1:6379> exec
1) OK
2) OK
3) (error) ERR value is not an integer or out of range # 运行时报错
4) "v1" # 其他命令正常执行
# 虽然中间有一条命令报错了,但是后面的指令依旧正常执行成功了。
# 所以说Redis单条指令保证原子性,但是Redis事务不能保证原子性。
**悲观锁:**很悲观,认为什么时候都会出现问题,无论做什么都会加锁!
**乐观锁:**很乐观,认为什么时候都不会出现问题,因此做什么都不会加锁!
watch key
监控指定数据,相当于乐观锁加锁如果事务执行成功,Redis 监控就会自动取消。
正常执行
127.0.0.1:6379> set money 100 # 余额:100
OK
127.0.0.1:6379> set use 0 # 支出:0
OK
127.0.0.1:6379> watch money # 监视money对象 (上锁)
OK
127.0.0.1:6379> multi # 事务正常结束,数据期间没有发生变动,这个时候就正常执行成功!
OK
127.0.0.1:6379(TX)> decrby money 20
QUEUED
127.0.0.1:6379(TX)> incrby use 20
QUEUED
127.0.0.1:6379(TX)> exec # 监视值没有被中途修改,事务正常执行
1) (integer) 80
2) (integer) 20
测试多线程修改值,使用watch可以当做redis的乐观锁操作(相当于getversion)
线程1:
127.0.0.1:6379> watch money # money上锁
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> decrby money 20
QUEUED
127.0.0.1:6379(TX)> incrby use 20
QUEUED
127.0.0.1:6379(TX)> # 此时事务并没有执行
启动另一个客户端模拟线程插队,线程2:
127.0.0.1:6379> incrby money 900 # 修改了线程1中监视的money
(integer) 1000
回到线程1,执行事务:
127.0.0.1:6379(TX)> exec # 执行之前,线程2修改了我们的值,这个时候就会导致事务执行失败
(nil) # 没有结果,说明事务执行失败
127.0.0.1:6379> get money # 线程2修改生效
"1000"
127.0.0.1:6379> get use # 线程1事务执行失败,数值没有被修改
"0"
使用
unwatch
进行解锁获取最新值,然后再加锁进行事务。
127.0.0.1:6379> unwatch # 刷新一个事务中已被监视的所有key。
OK
127.0.0.1:6379> watch money # 重新监视money对象 (上锁)
OK
127.0.0.1:6379(TX)> multi
OK
127.0.0.1:6379(TX)> decrby money 20
QUEUED
127.0.0.1:6379(TX)> incrby use 20
QUEUED
127.0.0.1:6379(TX)> exec # 对比监视值是否变化,如果没有,事务正常执行;否则执行失败!
1) (integer) 980
2) (integer) 20
注意:每次提交执行exec后都会自动释放锁,不管是否成功
使用Java来操作Redis,Jedis是Redis官方推荐使用的Java连接redis的客户端。
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>3.2.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.76version>
dependency>
连接数据库(https://blog.csdn.net/weixin_43878332/article/details/108741367)
修改redis的配置文件
在云端安全组和防火墙上,开放端口 6379
修改防火墙服务,添加端口并重新载入
firewall-cmd --state
firewall-cmd --zone=public --permanent --add-port=6379/tcp
firewall-cmd --reload
firewall-cmd --list-all
重启redis-server
重新进入Redis需要密码验证
[root@VM-4-12-centos src]# ./redis-server ../redis.conf
[root@VM-4-12-centos src]# ./redis-cli
127.0.0.1:6379> auth xxxxxx
OK
操作命令(TestPing.java)
public class TestPing {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.xx.xxx", 6379);
String response = jedis.ping();
System.out.println(response); // PONG
jedis.close();
}
}
断开连接
public class TestKey {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.xx.xxx", 6379);
System.out.println("清空数据库 —— " + jedis.flushAll());
System.out.println("判断某个键是否存在 —— "+jedis.exists("name"));
System.out.println("新增 —— " +jedis.set("name","name"));
System.out.println("新增 —— " +jedis.set("password","password"));
System.out.println("所有的键 —— " +jedis.keys("*"));
System.out.println("删除 password 的键值对 —— "+jedis.del("password"));
System.out.println("获取 name 的值 —— "+jedis.get("name"));
System.out.println("清空数据库 —— " + jedis.flushAll());
jedis.close();
}
}
/*
清空数据库 —— OK
判断某个键是否存在 —— false
新增 —— OK
新增 —— OK
所有的键 —— [password, name]
删除 password 的键值对 —— 1
获取 name 的值 —— name
清空数据库 —— OK
*/
public class TestTX {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.xx.xxx", 6379);
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "cwlin");
jsonObject.put("gender", "man");
jedis.flushDB();
Transaction multi = jedis.multi(); // 开启事务
String result = jsonObject.toJSONString();
try {
multi.set("user1", result);
// jedis.watch(user1); // 监听
multi.set("user2", result);
// int i = 1 / 0; // 代码抛出异常,事务执行失败!
multi.exec(); // 执行事务
} catch (Exception e) {
multi.discard(); // 放弃事务
} finally {
System.out.println(jedis.get("user1"));
System.out.println(jedis.get("user2"));
jedis.close(); // 关闭连接
}
}
}
SpringBoot 操作数据都是使用 SpringData:jpa、jdbc、mongodb、redis等
SpringData 也是和 SpringBoot 齐名的项目
说明:在 SpringBoot2.x 之后,原来使用的jedis 被替换为了 lettuce
?
<dependency>
<groupId>io.lettucegroupId>
<artifactId>lettuce-coreartifactId>
<version>5.3.5.RELEASEversion>
<scope>compilescope>
dependency>
Jedis 和 lettuce 区别:
在学习SpringBoot自动配置的原理时,整合一个组件并进行配置一定会有一个自动配置类xxxAutoConfiguration,并且在spring.factories中也一定能找到这个类的完全限定名,Redis也不例外
spring-boot-autoconfigure-2.3.7.RELEASE.jar
META-INF
spring.factories
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
点击查看 RedisAutoConfiguration 自动配置类,发现绑定了一个 RedisProperties 配置文件
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.springframework.boot.autoconfigure.data.redis;
import java.net.UnknownHostException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
public RedisAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean(name = {"redisTemplate"})
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
点击 RedisProperties 配置文件,查看 redis 可以配置的属性,以及连接池相关的配置。注意:使用时一定要使用 Lettuce 连接池
@ConfigurationProperties(
prefix = "spring.redis"
)
public class RedisProperties {
private int database = 0;
private String url;
private String host = "localhost";
private String password;
private int port = 6379; // 默认端口
private boolean ssl;
private Duration timeout;
private String clientName;
private RedisProperties.Sentinel sentinel;
private RedisProperties.Cluster cluster;
private final RedisProperties.Jedis jedis = new RedisProperties.Jedis();
private final RedisProperties.Lettuce lettuce = new RedisProperties.Lettuce();
//......
public static class Pool {
private int maxIdle = 8;
private int minIdle = 0;
private int maxActive = 8;
private Duration maxWait = Duration.ofMillis(-1);
private Duration timeBetweenEvictionRuns;
//......
}
}
回到 RedisAutoConfiguration 自动配置类,发现两个 Template 模板方法(对比RestTemplate、SqlSessionTemplate),可以使用这些 Template 来间接操作组件,RedisTemplate 和 StringRedisTemplate 分别用于操作 Redis 和 Redis 中的 String 数据类型。
@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
// 可以自定义一个redisTemplate来替换默认的Redis模板!
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
// 默认的 RedisTemplate 没有过多的设置,redis对象都是需要序列化!
// 两个泛型都是 Object, Object 的类型,我们后使用需要强制转换
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
// 由于String是redis中最常使用的类型,因此单独提出来一个bean!
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
再注意到 RedisAutoConfiguration 自动配置类导入的两个类
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
先看 Jedis 的实现类 JedisConnectionConfiguration,其中 @ConditionalOnClass 注解中有两个类 GenericObjectPool.class 和 Jedis.class 默认是不存在的,因此 Jedis 是无法生效的
@ConditionalOnClass({GenericObjectPool.class, JedisConnection.class, Jedis.class})
再看 Lettuce 的实现类 LettuceConnectionConfiguration,其中 @ConditionalOnClass 注解的 RedisClient.class 类是可用的,因此 Lettuce 是正常生效的
@ConditionalOnClass({RedisClient.class})
导入依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
编写配置文件(配置属性详见 RedisProperties.class)
# 配置redis
spring.redis.host=192.168.xxx.xx
spring.redis.port=6379
spring.redis.password=xxxxxx
# spring.redis.lettuce # 注意:使用连接池相关的配置时,一定要使用Lettuce连接池
使用RedisTemplate进行测试
package com.cwlin;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class Redis02SpringBootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
/* redisTemplate 操作不同的数据类型,API 和 Redis 中的是一样的
* opsForValue 类似于 Redis 中的 String
* opsForList 类似于 Redis 中的 List
* opsForSet 类似于 Redis 中的 Set
* opsForHash 类似于 Redis 中的 Hash
* opsForZSet 类似于 Redis 中的 ZSet
* opsForGeo 类似于 Redis 中的 Geospatial
* opsForHyperLogLog 类似于 Redis 中的 HyperLogLog
*/
// 除了基本的操作,常用的命令都可以直接通过redisTemplate操作,比如事务和CURD。和数据库相关的操作都需要通过连接操作。
/* 获取连接对象
* RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
* connection.flushDb();
* connection.flushAll();
*/
redisTemplate.opsForValue().set("myName", "cwlin");
System.out.println(redisTemplate.opsForValue().get("myName"));
}
}
测试结果
在 RedisAutoConfiguration 类的 redisTemplate 方法中用到了一个 RedisTemplate 的对象
@Bean
@ConditionalOnMissingBean(name = {"redisTemplate"})
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
默认的 RedisTemplate 内部的序列化配置是这样的,并查看这些序列化对象的赋值
public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware {
private boolean enableTransactionSupport = false;
private boolean exposeConnection = false;
private boolean initialized = false;
private boolean enableDefaultSerializer = true;
// 序列化器
@Nullable
private RedisSerializer<?> defaultSerializer;
@Nullable
private ClassLoader classLoader;
@Nullable
private RedisSerializer keySerializer = null;
@Nullable
private RedisSerializer valueSerializer = null;
@Nullable
private RedisSerializer hashKeySerializer = null;
@Nullable
private RedisSerializer hashValueSerializer = null;
private RedisSerializer<String> stringSerializer = RedisSerializer.string();
// ...
// 构造函数
public RedisTemplate() {
}
public void afterPropertiesSet() {
super.afterPropertiesSet();
boolean defaultUsed = false;
if (this.defaultSerializer == null) {
// 默认的序列化方式是采用JDK序列化器,我们可能会采用Json来序列化
this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
}
// 默认的RedisTemplate中的所有序列化器都是使用这个序列化器
if (this.enableDefaultSerializer) {
if (this.keySerializer == null) {
this.keySerializer = this.defaultSerializer;
defaultUsed = true;
}
if (this.valueSerializer == null) {
this.valueSerializer = this.defaultSerializer;
defaultUsed = true;
}
if (this.hashKeySerializer == null) {
this.hashKeySerializer = this.defaultSerializer;
defaultUsed = true;
}
if (this.hashValueSerializer == null) {
this.hashValueSerializer = this.defaultSerializer;
defaultUsed = true;
}
}
if (this.enableDefaultSerializer && defaultUsed) {
Assert.notNull(this.defaultSerializer, "default serializer null and not all serializers initialized");
}
if (this.scriptExecutor == null) {
this.scriptExecutor = new DefaultScriptExecutor(this);
}
this.initialized = true;
}
// ...
}
通过自定义 RedisTemplate 可以对其进行修改。
新建一个实体类
package com.cwlin.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
// 实体类序列化在后面加上 implements Serializable
public class User {
private String name;
private String age;
}
编写测试类,先不序列化实体类
package com.cwlin;
import com.cwlin.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class Redis02SpringBootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
// ...
}
@Test
public void test() throws JsonProcessingException {
User user = new User("cwlin","20");
// 使用 JSON 序列化
String jsonUser = new ObjectMapper().writeValueAsString(user);
// 这里直接传入一个对象
redisTemplate.opsForValue().set("user", jsonUser);
System.out.println(redisTemplate.opsForValue().get("user"));
}
}
执行结果:在旧版中,不进行序列化会报序列化的错误;而在新版中,可以正常执行!一般实体类都要序列化
**自定义 RedisTemplate 模板:**创建一个Bean加入容器,就会触发RedisTemplate上的条件注解,使得默认的RedisTemplate失效。
RedisSerializer
提供了多种序列化方案:
直接调用RedisSerializer的静态方法来返回序列化器,然后set;
初始化相应的实现类,然后set。
package com.cwlin.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
// 将template 泛型设置为
RedisTemplate<String, Object> template = new RedisTemplate();
// 连接工厂,不必修改
template.setConnectionFactory(redisConnectionFactory);
// 序列化设置
// String序列化器
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// Json序列化器:使用 jackson 解析任意的对象
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
// 使用 objectMapper 进行转义
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// key、hash的key 采用String序列化方式
template.setKeySerializer(stringRedisSerializer); // 和RedisSerializer.string()等价
template.setHashKeySerializer(stringRedisSerializer);
// value、hash的value 采用Jackson序列化方式
template.setValueSerializer(jackson2JsonRedisSerializer); // 和RedisSerializer.json()等价
template.setHashValueSerializer(jackson2JsonRedisSerializer);
// 把自定义的配置加入template中
template.afterPropertiesSet();
return template;
}
}
使用上述模板后,默认的RedisTemplate自动失效。只要对实体类进行序列化,就不会产生乱码了!如果去获取这个对象或者中文字符串的时候还是会显示转义字符,那么只需要在启动 Redis 客户端的时候加上 –raw
即可
redis-cli --raw -p 6379
使用 RedisTemplate 需要频繁调用 .opForxxx
,然后才能进行对应的操作,这样使用起来代码效率低下,工作中一般不会这样使用,而是将这些常用的公共API抽取出来封装成为一个工具类,然后直接使用工具类来间接操作Redis,不但效率高并且易用。
工具类参考博客:
简单测试一下:
package com.cwlin;
import com.cwlin.pojo.User;
import com.cwlin.utils.RedisUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class Redis02SpringBootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private RedisUtil redisUtil;
@Test
public void utilTest() {
redisUtil.set("name", "cwlin");
System.out.println(redisUtil.get("name")); //会有反斜杠转义符
}
@Test
void contextLoads() {
// ...
}
@Test
public void test() throws JsonProcessingException {
// ...
}
}
units:容量单位不区分大小写,G和GB有区别
# Note on units: when memory size is needed, it is possible to specify
# it in the usual form of 1k 5GB 4M and so forth:
#
# 1k => 1000 bytes
# 1kb => 1024 bytes
# 1m => 1000000 bytes
# 1mb => 1024*1024 bytes
# 1g => 1000000000 bytes
# 1gb => 1024*1024*1024 bytes
#
# units are case insensitive so 1GB 1Gb 1gB are all the same.
INCLUDES:可以使用 include 组合多个配置问
################################## INCLUDES ###################################
# Include one or more other config files here. This is useful if you
# have a standard template that goes to all Redis servers but also need
# to customize a few per-server settings. Include files can include
# other files, so use this wisely.
#
# Notice option "include" won't be rewritten by command "CONFIG REWRITE"
# from admin or Redis Sentinel. Since Redis always uses the last processed
# line as value of a configuration directive, you'd better put includes
# at the beginning of this file to avoid overwriting config change at runtime.
#
# If instead you are interested in using includes to override configuration
# options, it is better to use include as the last line.
#
# include /path/to/local.conf
# include /path/to/other.conf
MODULES:加载其他的模块(略)
################################## MODULES #####################################
# Load modules at startup. If the server is not able to load modules
# it will abort. It is possible to use multiple loadmodule directives.
#
# loadmodule /path/to/my_module.so
# loadmodule /path/to/other_module.so
NETWORK:网络配置(重点!)
################################## NETWORK #####################################
# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 loopback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# bind 127.0.0.1
# Protected mode is a layer of security protection, in order to avoid that
# Redis instances left open on the internet are accessed and exploited.
#
# When protected mode is on and if:
#
# 1) The server is not binding explicitly to a set of addresses using the
# "bind" directive.
# 2) No password is configured.
#
# The server only accepts connections from clients connecting from the
# IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain
# sockets.
#
# By default protected mode is enabled. You should disable it only if
# you are sure you want clients from other hosts to connect to Redis
# even if no authentication is configured, nor a specific set of interfaces
# are explicitly listed using the "bind" directive.
protected-mode no
# Accept connections on the specified port, default is 6379 (IANA #815344).
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379
# TCP listen() backlog. # TCP积压工作
#
# In high requests-per-second environments you need an high backlog in order
# to avoid slow clients connections issues. Note that the Linux kernel
# will silently truncate it to the value of /proc/sys/net/core/somaxconn so
# make sure to raise both the value of somaxconn and tcp_max_syn_backlog
# in order to get the desired effect.
tcp-backlog 511
# Unix socket. # Unix套接字
#
# Specify the path for the Unix socket that will be used to listen for
# incoming connections. There is no default, so Redis will not listen
# on a unix socket when not specified.
#
# unixsocket /tmp/redis.sock
# unixsocketperm 700
# Close the connection after a client is idle for N seconds (0 to disable)
timeout 5000 # 当空闲5000秒后关闭
# TCP keepalive.
#
# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
# of communication. This is useful for two reasons:
#
# 1) Detect dead peers.
# 2) Take the connection alive from the point of view of network
# equipment in the middle.
#
# On Linux, the specified value (in seconds) is the period used to send ACKs.
# Note that to close the connection the double of the time is needed.
# On other kernels the period depends on the kernel configuration.
#
# A reasonable value for this option is 300 seconds, which is the new
# Redis default starting with Redis 3.2.1.
tcp-keepalive 300 # 每300秒没有收到上层协议的数据,就发送一个空报文,来确认对方是否还在线
GENERAL:通用配置(进程、日志等)
################################# GENERAL #####################################
# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize yes
# If you run Redis from upstart or systemd, Redis can interact with your
# supervision tree. Options:
# supervised no - no supervision interaction
# supervised upstart - signal upstart by putting Redis into SIGSTOP mode
# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
# supervised auto - detect upstart or systemd method based on
# UPSTART_JOB or NOTIFY_SOCKET environment variables
# Note: these supervision methods only signal "process is ready."
# They do not enable continuous liveness pings back to your supervisor.
supervised no
# If a pid file is specified, Redis writes it where specified at startup
# and removes it at exit.
#
# When the server runs non daemonized, no pid file is created if none is
# specified in the configuration. When the server is daemonized, the pid file
# is used even if not specified, defaulting to "/var/run/redis.pid".
#
# Creating a pid file is best effort: if Redis is not able to create it
# nothing bad happens, the server will start and run normally.
pidfile /www/server/redis/redis.pid
# Specify the server verbosity level.
# This can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel notice
# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile "/www/server/redis/redis.log"
# To enable logging to the system logger, just set 'syslog-enabled' to yes,
# and optionally update the other syslog parameters to suit your needs.
# syslog-enabled no
# Specify the syslog identity.
# syslog-ident redis
# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7.
# syslog-facility local0
# Set the number of databases. The default database is DB 0, you can select
# a different one on a per-connection basis using SELECT where
# dbid is a number between 0 and 'databases'-1
databases 16
# By default Redis shows an ASCII art logo only when started to log to the
# standard output and if the standard output is a TTY. Basically this means
# that normally a logo is displayed only in interactive sessions.
#
# However it is possible to force the pre-4.0 behavior and always show a
# ASCII art logo in startup logs by setting the following option to yes.
always-show-logo yes
SNAPSHOTTING(快照):持久化规则
持久化:在一定时间(秒)内,对数据库执行了一定数量的写操作,则会把数据持久化到文件 .rdb. aof。学习持久化后,可以自定义这个配置!
持久化方式:RDB 和 AOF。
由于 Redis 是基于内存的数据库(内存数据库),需要将数据由内存持久化到文件中。如果没有持久化,那么数据断电及失!
################################ SNAPSHOTTING ################################
#
# Save the DB on disk:
#
# save
#
# Will save the DB if both the given number of seconds and the given
# number of write operations against the DB occurred.
#
# In the example below the behaviour will be to save:
# after 900 sec (15 min) if at least 1 key changed
# after 300 sec (5 min) if at least 10 keys changed
# after 60 sec if at least 10000 keys changed
#
# Note: you can disable saving completely by commenting out all "save" lines.
#
# It is also possible to remove all the previously configured save
# points by adding a save directive with a single empty string argument
# like in the following example:
#
# save ""
save 900 1 # 如果 900 秒内至少有 1 个key进行了修改,我们就进行持久化操作
save 300 10 # 如果 300 秒内至少有 10 个key进行了修改,我们就进行持久化操作
save 60 10000 # 如果 60 秒内至少有 10000 个key进行了修改,我们就进行持久化操作
# By default Redis will stop accepting writes if RDB snapshots are enabled
# (at least one save point) and the latest background save failed.
# This will make the user aware (in a hard way) that data is not persisting
# on disk properly, otherwise chances are that no one will notice and some
# disaster will happen.
#
# If the background saving process will start working again Redis will
# automatically allow writes again.
#
# However if you have setup your proper monitoring of the Redis server
# and persistence, you may want to disable this feature so that Redis will
# continue to work as usual even if there are problems with disk,
# permissions, and so forth.
stop-writes-on-bgsave-error yes # 持久化出错后,是否继续工作
# Compress string objects using LZF when dump .rdb databases?
# For default that's set to 'yes' as it's almost always a win.
# If you want to save some CPU in the saving child set it to 'no' but
# the dataset will likely be bigger if you have compressible values or keys.
rdbcompression yes # 是否压缩rdb文件,需要消耗一些cpu的资源
# Since version 5 of RDB a CRC64 checksum is placed at the end of the file.
# This makes the format more resistant to corruption but there is a performance
# hit to pay (around 10%) when saving and loading RDB files, so you can disable it
# for maximum performances.
#
# RDB files created with checksum disabled have a checksum of zero that will
# tell the loading code to skip the check.
rdbchecksum yes # 在保存rdb文件时,进行错误的检查校验
# The filename where to dump the DB
dbfilename dump.rdb # 持久化生成的rdb文件名
# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /www/server/redis/ # rdb文件保存的目录,默认为当前目录
REPLICATION:主从复制(这里暂时不展开介绍)
################################# REPLICATION #################################
# Master-Replica replication. Use replicaof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
# +------------------+ +---------------+
# | Master | ---> | Replica |
# | (receive writes) | | (exact copy) |
# +------------------+ +---------------+
#
# 1) Redis replication is asynchronous, but you can configure a master to
# stop accepting writes if it appears to be not connected with at least
# a given number of replicas.
# 2) Redis replicas are able to perform a partial resynchronization with the
# master if the replication link is lost for a relatively small amount of
# time. You may want to configure the replication backlog size (see the next
# sections of this file) with a sensible value depending on your needs.
# 3) Replication is automatic and does not need user intervention. After a
# network partition replicas automatically try to reconnect to masters
# and resynchronize with them.
# ......
SECURITY:安全配置
requirepass:设置密码认证,在云服务器上一定要设置密码!
通过修改配置文件进行设置,记得重启 redis。
通过命令进行设置:config set requirepass xxxxxx
,关闭进程后密码会失效。
使用密码进行登录:
127.0.0.1:6379> ping
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth xxxxxx
OK
Redis 6.0 后,建议使用外部 ACL代替。(略)
################################## SECURITY ###################################
# Require clients to issue AUTH before processing any other
# commands. This might be useful in environments in which you do not trust
# others with access to the host running redis-server.
#
# This should stay commented out for backward compatibility and because most
# people do not need auth (e.g. they run their own servers).
#
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
requirepass xxxxxx
# Command renaming.
#
# It is possible to change the name of dangerous commands in a shared
# environment. For instance the CONFIG command may be renamed into something
# hard to guess so that it will still be available for internal-use tools
# but not available for general clients.
#
# Example:
#
# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52
#
# It is also possible to completely kill a command by renaming it into
# an empty string:
#
# rename-command CONFIG ""
#
# Please note that changing the name of commands that are logged into the
# AOF file or transmitted to replicas may cause problems.
CLIENT:设置连接 Redis 的最大客户端数量
################################### CLIENTS ####################################
# Set the max number of connected clients at the same time. By default
# this limit is set to 10000 clients, however if the Redis server is not
# able to configure the process file limit to allow for the specified limit
# the max number of allowed clients is set to the current file limit
# minus 32 (as Redis reserves a few file descriptors for internal uses).
#
# Once the limit is reached Redis will close all the new connections sending
# an error 'max number of clients reached'.
#
# maxclients 10000
MEMORY MANAGEMENT:内存管理
config set maxmemory-policy noeviction
############################## MEMORY MANAGEMENT ################################
# Set a memory usage limit to the specified amount of bytes.
# When the memory limit is reached Redis will try to remove keys
# according to the eviction policy selected (see maxmemory-policy).
#
# If Redis can't remove keys according to the policy, or if the policy is
# set to 'noeviction', Redis will start to reply with errors to commands
# that would use more memory, like SET, LPUSH, and so on, and will continue
# to reply to read-only commands like GET.
#
# This option is usually useful when using Redis as an LRU or LFU cache, or to
# set a hard memory limit for an instance (using the 'noeviction' policy).
#
# WARNING: If you have replicas attached to an instance with maxmemory on,
# the size of the output buffers needed to feed the replicas are subtracted
# from the used memory count, so that network problems / resyncs will
# not trigger a loop where keys are evicted, and in turn the output
# buffer of replicas is full with DELs of keys evicted triggering the deletion
# of more keys, and so forth until the database is completely emptied.
#
# In short... if you have replicas attached it is suggested that you set a lower
# limit for maxmemory so that there is some free RAM on the system for replica
# output buffers (but this is not needed if the policy is 'noeviction').
#
# maxmemory
# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#
# volatile-lru -> Evict using approximated LRU among the keys with an expire set.
# allkeys-lru -> Evict any key using approximated LRU.
# volatile-lfu -> Evict using approximated LFU among the keys with an expire set.
# allkeys-lfu -> Evict any key using approximated LFU.
# volatile-random -> Remove a random key among the ones with an expire set.
# allkeys-random -> Remove a random key, any key.
# volatile-ttl -> Remove the key with the nearest expire time (minor TTL)
# noeviction -> Don't evict anything, just return an error on write operations.
#
# LRU means Least Recently Used
# LFU means Least Frequently Used
#
# Both LRU, LFU and volatile-ttl are implemented using approximated
# randomized algorithms.
#
# Note: with any of the above policies, Redis will return an error on write
# operations, when there are no suitable keys for eviction.
#
# At the date of writing these commands are: set setnx setex append
# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
# getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy noeviction
# LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated
# algorithms (in order to save memory), so you can tune it for speed or
# accuracy. For default Redis will check five keys and pick the one that was
# used less recently, you can change the sample size using the following
# configuration directive.
#
# The default of 5 produces good enough results. 10 Approximates very closely
# true LRU but costs more CPU. 3 is faster but not very accurate.
#
# maxmemory-samples 5
# Starting from Redis 5, by default a replica will ignore its maxmemory setting
# (unless it is promoted to master after a failover or manually). It means
# that the eviction of keys will be just handled by the master, sending the
# DEL commands to the replica as keys evict in the master side.
#
# This behavior ensures that masters and replicas stay consistent, and is usually
# what you want, however if your replica is writable, or you want the replica to have
# a different memory setting, and you are sure all the writes performed to the
# replica are idempotent, then you may change this default (but be sure to understand
# what you are doing).
#
# Note that since the replica by default does not evict, it may end using more
# memory than the one set via maxmemory (there are certain buffers that may
# be larger on the replica, or data structures may sometimes take more memory and so
# forth). So make sure you monitor your replicas and make sure they have enough
# memory to never hit a real out-of-memory condition before the master hits
# the configured maxmemory setting.
#
# replica-ignore-maxmemory yes
APPEND ONLY MODE:AOF 配置
############################## APPEND ONLY MODE ###############################
# By default Redis asynchronously dumps the dataset on disk. This mode is
# good enough in many applications, but an issue with the Redis process or
# a power outage may result into a few minutes of writes lost (depending on
# the configured save points).
#
# The Append Only File is an alternative persistence mode that provides
# much better durability. For instance using the default data fsync policy
# (see later in the config file) Redis can lose just one second of writes in a
# dramatic event like a server power outage, or a single write if something
# wrong with the Redis process itself happens, but the operating system is
# still running correctly.
#
# AOF and RDB persistence can be enabled at the same time without problems.
# If the AOF is enabled on startup Redis will load the AOF, that is the file
# with the better durability guarantees.
#
# Please check http://redis.io/topics/persistence for more information.
appendonly no
# The name of the append only file (default: "appendonly.aof")
appendfilename "appendonly.aof"
# The fsync() call tells the Operating System to actually write data on disk
# instead of waiting for more data in the output buffer. Some OS will really flush
# data on disk, some other OS will just try to do it ASAP.
#
# Redis supports three different modes:
#
# no: don't fsync, just let the OS flush the data when it wants. Faster.
# always: fsync after every write to the append only log. Slow, Safest.
# everysec: fsync only one time every second. Compromise.
#
# The default is "everysec", as that's usually the right compromise between
# speed and data safety. It's up to you to understand if you can relax this to
# "no" that will let the operating system flush the output buffer when
# it wants, for better performances (but if you can live with the idea of
# some data loss consider the default persistence mode that's snapshotting),
# or on the contrary, use "always" that's very slow but a bit safer than
# everysec.
#
# More details please check the following article:
# http://antirez.com/post/redis-persistence-demystified.html
#
# If unsure, use "everysec".
# appendfsync always
appendfsync everysec
# appendfsync no
# When the AOF fsync policy is set to always or everysec, and a background
# saving process (a background save or AOF log background rewriting) is
# performing a lot of I/O against the disk, in some Linux configurations
# Redis may block too long on the fsync() call. Note that there is no fix for
# this currently, as even performing fsync in a different thread will block
# our synchronous write(2) call.
RDB
的时候,redis
的主线程是不会做 io
操作的,主线程会 fork
一个子线程来完成该操作
save
命令,会立刻对当前内存中的数据进行持久化,但是会阻塞,也就是不接受其他操作了。save
是同步命令,会占用Redis的主进程。若Redis数据非常多时,save
命令执行速度会非常慢,阻塞所有客户端的请求。bgsave
是异步进行,进行持久化的时候,redis
还可以将继续响应客户端请求。命令 | save | bgsave |
---|---|---|
IO类型 | 同步 | 异步 |
阻塞? | 是 | 是(阻塞发生在fock(),通常非常快) |
复杂度 | O(n) | O(n) |
优点 | 不会消耗额外的内存 | 不阻塞客户端命令 |
缺点 | 阻塞客户端命令 | 需要fock子进程,消耗内存 |
只需要把 RDB 文件放到 Redis 的启动目录,Redis 启动的时候就会自动检查 dump.rdb 文件,并恢复数据。
查看 Redis 的启动目录,即 RDB 文件需要存在的位置:
127.0.0.1:6379> config get dir
1) "dir"
2) "/www/server/redis" # 如果在这个目录下存在dump.rdb文件,启动就会自动恢复其中的数据
在生产环境下,一般会把这个 RDB 文件进行备份。在实际使用中,RDB 都是放在从机上面备用。
AOF 保存信息的文件的文件名为 appendonly.aof。在实际使用中,很少用到 AOF。
如果要使用AOF,需要修改配置文件:appendonly yes
,并重启 redis。
appendonly no # 默认不开启AOF模式
appendfilename "appendonly.aof" # 默认文件名
如果 AOF 文件出错,此时 redis 是无法启动的,因此需要修改 AOF 文件。
redis 给我们提供了一个工具 redis-check-aof
来修复 AOF 文件:
redis-check-aof --fix appendonly.aof
如果文件正常,重启就可以直接恢复了。
优点
缺点
相对于数据文件来说,AOF 的文件体积远远大于 RDB,恢复备份速度比 RDB 慢!
根据所使用的 fsync 策略,AOF 的速度可能会慢于 RDB 。每次读写都同步的话,有一定的性能压力。
# appendfsync always # 每次修改都会 sync,消耗性能!
appendfsync everysec # 每秒执行一次 sync,可能会丢失这 1s 的数据!
# appendfsync no # 不执行 sync,这个时候操作系统自己同步数据,速度最快!
AOF 都是 IO 操作,运行效率也要比 RDB 慢,因此 Redis 默认配置是 RDB 持久化。
RDB | AOF | |
---|---|---|
启动优先级 | 低 | 高 |
体积 | 小 | 大 |
恢复速度 | 快 | 慢 |
数据安全性 | 丢数据 | 根据策略决定 |
RDB的优点
RDB 是一个非常紧凑的文件,它保存了某个时间点得数据集,非常适用于数据集的备份,比如你可以在每个小时报保存一下过去24小时内的数据,同时每天保存过去30天的数据,这样即使出了问题你也可以根据需求恢复到不同版本的数据集。
RDB 是一个紧凑的单一文件,很方便传送到另一个远端数据中心或者亚马逊的 S3(可能加密),非常适用于灾难恢复。
RDB 在保存 RDB 文件时父进程唯一需要做的就是 fork 出一个子进程,接下来的工作全部由子进程来做,父进程不需要再做其他 IO 操作,所以 RDB 持久化方式可以最大化redis的性能。
与 AOF 相比,在恢复大的数据集的时候,RDB 方式会更快一些。
RDB的缺点
如果你希望在 redis 意外停止工作(例如电源中断)的情况下丢失的数据最少的话,那么 RDB 不适合你。虽然你可以配置不同的 save 时间点(例如每隔5分钟并且对数据集有100个写的操作),是 Redis 要完整的保存整个数据集是一个比较繁重的工作,你通常会每隔5分钟或者更久做一次完整的保存,万一在Redis 意外宕机,你可能会丢失几分钟的数据。
RDB 需要经常 fork 子进程来保存数据集到硬盘上,当数据集比较大的时候,fork 的过程是非常耗时的,可能会导致 Redis 在一些毫秒级内不能响应客户端的请求。如果数据集巨大并且 CPU 性能不是很好的情况下,这种情况会持续1秒,AOF 也需要 fork,但是你可以调节重写日志文件的频率来提高数据集的耐久度。
AOF 优点
使用 AOF 会让你的 Redis 更加耐久,你可以使用不同的fsync策略:无fsync,每秒fsync,每次写的时候fsync。使用默认的每秒fsync策略,Redis的性能依然很好(fsync是由后台线程进行处理的,主线程会尽力处理客户端请求),一旦出现故障,你最多丢失1秒的数据。
AOF 文件是一个只进行追加的日志文件,所以不需要写入 seek,即使由于某些原因(磁盘空间已满,写的过程中宕机等等)未执行完整的写入命令,你也可使用 redis-check-aof 工具修复这些问题。
Redis 可以在 AOF 文件体积变得过大时,自动地在后台对 AOF 进行重写,重写后的新 AOF 文件包含了恢复当前数据集所需的最小命令集合。 整个重写操作是绝对安全的,因为 Redis 在创建新 AOF 文件的过程中,会继续将命令追加到现有的 AOF 文件里面,即使重写过程中发生停机,现有的 AOF 文件也不会丢失。 而一旦新 AOF 文件创建完毕,Redis 就会从旧 AOF 文件切换到新 AOF 文件,并开始对新 AOF 文件进行追加操作。
AOF 文件有序地保存了对数据库执行的所有写入操作,这些写入操作以 Redis 协议的格式保存,因此 AOF 文件的内容非常容易被人读懂,对文件进行分析(parse)也很轻松。导出(export)AOF 文件也非常简单:举个例子,如果你不小心执行了 FLUSHALL 命令,但只要 AOF 文件未被重写,那么只要停止服务器,移除 AOF 文件末尾的 FLUSHALL 命令,并重启 Redis,就可以将数据集恢复到 FLUSHALL 执行之前的状态。
AOF 缺点
对于相同的数据集来说,AOF 文件的体积通常要大于 RDB 文件的体积。
根据所使用的 fsync 策略,AOF 的速度可能会慢于 RDB 。 在一般情况下, 每秒 fsync 的性能依然非常高, 而关闭 fsync 可以让 AOF 的速度和 RDB 一样快, 即使在高负荷之下也是如此。 不过在处理巨大的写入载入时,RDB 可以提供更有保证的最大延迟时间(latency)。
命令 | 描述 |
---|---|
PSUBSCRIBE pattern [pattern..] |
订阅一个或多个符合给定模式的频道。 |
PUNSUBSCRIBE pattern [pattern..] |
退订一个或多个符合给定模式的频道。 |
PUBSUB subcommand [argument[argument]] |
查看订阅与发布系统状态。 |
PUBLISH channel message |
向指定频道发布消息 |
SUBSCRIBE channel [channel..] |
订阅给定的一个或多个频道。 |
SUBSCRIBE channel [channel..] |
退订一个或多个频道 |
------------------消息订阅端----------------------
127.0.0.1:6379> subscribe chwlyn # 订阅chwlyn频道
Reading messages... (press Ctrl-C to quit) # 等待接收消息
1) "subscribe" # 订阅成功的消息
2) "chwlyn"
3) (integer) 1
1) "message" # 接收到来自chwlyn频道的消息 "hello,world!"
2) "chwlyn"
3) "hello,world!"
1) "message" # 接收到来自chwlyn频道的消息 "ding."
2) "chwlyn"
3) "ding."
------------------消息发布端----------------------
127.0.0.1:6379> publish chwlyn hello,world!
(integer) 1
127.0.0.1:6379> publish chwlyn ding.
(integer) 1
127.0.0.1:6379>
-----------------查看活跃的频道--------------------
127.0.0.1:6379> pubsub channels
1) "chwlyn"
一般来说,要将Redis运用于工程项目中,只使用一台Redis是万万不能的(宕机),原因如下:
例如电商网站上的商品,一般都是一次上传,无数次浏览的,说专业点也就是“多读少写”。对于这种场景,一般可以使用如下这种架构,称作“一主三从”:
主从复制,读写分离!80% 的情况下都是在进行读操作!一主二从的架构经常使用,这可以减缓服务器的压力。在公司中,主从复制是必须要使用的,因为在真实的项目中不可能单机使用 Redis!
简单来说,有以下三个原因:
replication
模块。127.0.0.1:6379> info replication # 查看当前库的信息
# Replication
role:master # 角色:master
connected_slaves:0 # 从机数量:当前没有从机
master_failover_state:no-failover
master_replid:5c3d40b552d730b0d5ff57fe15aad9e74e8025f0
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
既然需要启动多个服务,那么就需要多个配置文件。复制三个配置文件,修改对应的信息:
[root@VM-4-12-centos ~]# cd /www/server/redis
[root@VM-4-12-centos redis]# cp redis.conf myconfig/redis6379.conf
[root@VM-4-12-centos redis]# cp redis.conf myconfig/redis6380.conf
[root@VM-4-12-centos redis]# cp redis.conf myconfig/redis6381.conf
[root@VM-4-12-centos redis]# cd myconfig
[root@VM-4-12-centos myconfig]# ls
redis6379.conf redis6380.conf redis6381.conf
[root@VM-4-12-centos myconfig]# vim redis6379.conf
[root@VM-4-12-centos myconfig]# vim redis6380.conf
[root@VM-4-12-centos myconfig]# vim redis6381.conf
启动四个 Linux 连接(1 主、2 从、1 测试),用于开启单机多服务集群:
[root@VM-4-12-centos src]# ./redis-server ../myconfig/redis6379.conf
[root@VM-4-12-centos src]# ./redis-server ../myconfig/redis6380.conf
[root@VM-4-12-centos src]# ./redis-server ../myconfig/redis6381.conf
[root@VM-4-12-centos src]# ps -ef|grep redis
root 1727 1 0 18:12 ? 00:00:00 ./redis-server *:6379
root 2864 1 0 18:12 ? 00:00:00 ./redis-server *:6380
root 3427 1 0 18:12 ? 00:00:00 ./redis-server *:6381
root 4114 11002 0 18:13 pts/3 00:00:00 grep --color=auto redis
默认情况下,每台 Redis 服务器都是主节点;一般情况下只需要配置从机!在这里,我们对集群进行如下配置:一主(79)二从(80,81)。
使用 SLAVEOF host port
为从机配置主机。配置完成后,两台从机都显示连接到主机,但是主机显示连接到的从机数量为 0:
[root@VM-4-12-centos src]# ./redis-cli -p 6380
127.0.0.1:6380> auth xxxxxx
OK
127.0.0.1:6380> slaveof 127.0.0.1 6379 # 配置主机
OK
127.0.0.1:6380> info replication
# Replication
role:slave # 当前角色是从机
master_host:127.0.0.1 # 主机信息
master_port:6379
master_link_status:down
master_last_io_seconds_ago:-1
master_sync_in_progress:0
slave_read_repl_offset:1
slave_repl_offset:1
master_link_down_since_seconds:-1
slave_priority:100
slave_read_only:1
replica_announced:1
connected_slaves:0
master_failover_state:no-failover
master_replid:166d778584a9203796205ff4d1dc5001cd69c0c4
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
[root@VM-4-12-centos src]# ./redis-cli -p 6381
127.0.0.1:6381> auth xxxxxx
OK
127.0.0.1:6381> slaveof 127.0.0.1 6379 #配置主机
OK
127.0.0.1:6381> info replication
# Replication
role:slave # 当前角色是从机
master_host:127.0.0.1 # 主机信息
master_port:6379
master_link_status:down
master_last_io_seconds_ago:-1
master_sync_in_progress:0
slave_read_repl_offset:1
slave_repl_offset:1
master_link_down_since_seconds:-1
slave_priority:100
slave_read_only:1
replica_announced:1
connected_slaves:0
master_failover_state:no-failover
master_replid:3565a21bb00fce7005456676a783e654c612cb0d
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
[root@VM-4-12-centos src]# ./redis-cli -p 6379
127.0.0.1:6379> auth xxxxxx
OK
127.0.0.1:6379> info replication
# Replication
role:master # 当前角色是主机
connected_slaves:0 # 连接从机的数量
master_failover_state:no-failover
master_replid:d0ce0bacb986217bfeb7ea79c8ba288d0b2a989f
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
查看从机log日志文件发现错误信息,发现主机master要求密码验证:
MASTER aborted replication with an error: NOAUTH Authentication required.
对于 Redis 集群,如果设置了 requirepass,则一定要在从机的配置文件中设置 masterauth,否则从节点无法正常工作。
127.0.0.1:6379> info replication
# Replication
role:master # 当前角色是主机
connected_slaves:2 # 连接从机的数量变为2个
slave0:ip=127.0.0.1,port=6380,state=online,offset=126,lag=0 # 从机0的配置
slave1:ip=127.0.0.1,port=6381,state=online,offset=126,lag=1 # 从机1的配置
master_failover_state:no-failover
master_replid:bef0bb203fb9076d4c7edba33764fd5ebc3a0ecc
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:126
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:126
这里是使用命令搭建,是暂时的!真实开发中应该在从机的配置文件中进行配置,这样的话是永久的。
################################# REPLICATION #################################
# Master-Replica replication. Use replicaof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
# +------------------+ +---------------+
# | Master | ---> | Replica |
# | (receive writes) | | (exact copy) |
# +------------------+ +---------------+
#
# 1) Redis replication is asynchronous, but you can configure a master to
# stop accepting writes if it appears to be not connected with at least
# a given number of replicas.
# 2) Redis replicas are able to perform a partial resynchronization with the
# master if the replication link is lost for a relatively small amount of
# time. You may want to configure the replication backlog size (see the next
# sections of this file) with a sensible value depending on your needs.
# 3) Replication is automatic and does not need user intervention. After a
# network partition replicas automatically try to reconnect to masters
# and resynchronize with them.
#
# replicaof # 配置主机信息
# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the replica to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the replica request.
#
# masterauth #若主机需要密码验证,配置主机密码
从机只能读不能写,主机可读可写但是多用于写。
127.0.0.1:6380> set name cwlin # 从机6380写入失败
(error) READONLY You can't write against a read only replica.
127.0.0.1:6381> set name cwlin # 从机6381写入失败
(error) READONLY You can't write against a read only replica.
127.0.0.1:6379> set name cwlin # 主机6379写入成功
OK
127.0.0.1:6379> get name # 主机6379读取成功
"cwlin"
127.0.0.1:6380> get name # 从机6380读取成功
"cwlin"
127.0.0.1:6381> keys * # 从机6381读取成功
1) "name"
当主机断电宕机后,默认情况下从机的角色不会发生变化,集群中只是失去了写操作,当主机恢复以后,又会连接上从机恢复原状。
当从机断电宕机后,**若不是使用配置文件配置从机,即使用命令行,那么再次启动后作为主机是无法获取之前主机的数据的。**若此时重新配置称为从机,又可以获取到主机的所有数据。这里就要提到一个同步原理(详见 10.5)。
第 2 条中提到,默认情况下,主机故障后,不会出现新的主机,有三种方式可以产生新的主机:
slaveof no one
,这样执行以后从机会独立出来成为一个主机,其他节点就可以手动重新连接到新的主节点;在 myconfig 文件夹下,配置哨兵配置文件 sentinel.conf:
[root@VM-4-12-centos myconfig]# ls
redis6379.conf redis6380.conf redis6381.conf
[root@VM-4-12-centos myconfig]# vim sentinel.conf
# sentinel monitor 被监控的名称 host port 1
# 最后一位 1:当一个哨兵主观认为主机断开,就可以客观认为主机故障,然后开始选举新的主机
sentinel monitor mymaster 127.0.0.1 6379 1
# 连接master的密码
sentinel auth-pass mymaster chwlyn199809
protected-mode no
启动哨兵模式:
[root@VM-4-12-centos src]# ./redis-sentinel ../myconfig/sentinel.conf
9099:X 24 Jan 2022 21:52:20.053 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
9099:X 24 Jan 2022 21:52:20.053 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=9099, just started
9099:X 24 Jan 2022 21:52:20.053 # Configuration loaded
9099:X 24 Jan 2022 21:52:20.053 * monotonic clock: POSIX clock_gettime
_._
_.-``__ ''-._
_.-`` `. `_. ''-._ Redis 6.2.6 (00000000/0) 64 bit
.-`` .-```. ```\/ _.,_ ''-._
( ' , .-` | `, ) Running in sentinel mode
|`-._`-...-` __...-.``-._|'` _.-'| Port: 26379
| `-._ `._ / _.-' | PID: 9099
`-._ `-._ `-./ _.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' | https://redis.io
`-._ `-._`-.__.-'_.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' |
`-._ `-._`-.__.-'_.-' _.-'
`-._ `-.__.-' _.-'
`-._ _.-'
`-.__.-'
9099:X 24 Jan 2022 21:52:20.060 # Sentinel ID is a7f156e1e4140e5693632d1f5fe7ff208e2c9796
9099:X 24 Jan 2022 21:52:20.060 # +monitor master mymaster 127.0.0.1 6379 quorum 1
9099:X 24 Jan 2022 21:52:20.061 * +slave slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:52:20.066 * +slave slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6379
此时,哨兵监视着主机 6379。如果我们断开主机,那么当一个哨兵认为主机断开时,将自动选取新的主机,原先的主机也被加入从机中。
9099:X 24 Jan 2022 21:54:09.038 # +sdown master mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:09.038 # +odown master mymaster 127.0.0.1 6379 #quorum 1/1 # 一个哨兵认为主机断开
9099:X 24 Jan 2022 21:54:09.038 # +new-epoch 1
9099:X 24 Jan 2022 21:54:09.038 # +try-failover master mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:09.044 # +vote-for-leader a7f156e1e4140e5693632d1f5fe7ff208e2c9796 1
9099:X 24 Jan 2022 21:54:09.044 # +elected-leader master mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:09.044 # +failover-state-select-slave master mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:09.134 # +selected-slave slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:09.134 * +failover-state-send-slaveof-noone slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:09.192 * +failover-state-wait-promotion slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:09.290 # +promoted-slave slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:09.290 # +failover-state-reconf-slaves master mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:09.385 * +slave-reconf-sent slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:10.298 * +slave-reconf-inprog slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:10.298 * +slave-reconf-done slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:10.353 # +failover-end master mymaster 127.0.0.1 6379
9099:X 24 Jan 2022 21:54:10.353 # +switch-master mymaster 127.0.0.1 6379 127.0.0.1 6380 # 自动选取新的主机
9099:X 24 Jan 2022 21:54:10.353 * +slave slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6380
9099:X 24 Jan 2022 21:54:10.353 * +slave slave 127.0.0.1:6379 127.0.0.1 6379 @ mymaster 127.0.0.1 6380 # 原先的主机也被加入从机中
9099:X 24 Jan 2022 21:54:40.379 # +sdown slave 127.0.0.1:6379 127.0.0.1 6379 @ mymaster 127.0.0.1 6380
若此时再次打开主机,那么原主机将成为新主机的从机,归并到新的主机下,这就是哨兵模式的规则!
9099:X 24 Jan 2022 21:59:58.771 # -sdown slave 127.0.0.1:6379 127.0.0.1 6379 @ mymaster 127.0.0.1 6380
9099:X 24 Jan 2022 22:00:08.765 * +convert-to-slave slave 127.0.0.1:6379 127.0.0.1 6379 @ mymaster 127.0.0.1 6380
完整的哨兵模式配置文件 sentinel.conf
# Example sentinel.conf
# 哨兵sentinel实例运行的端口 默认26379
port 26379
# 哨兵sentinel的工作目录
dir /tmp
# 哨兵sentinel监控的redis主节点的 ip port
# master-name 可以自己命名的主节点名字 只能由字母A-z、数字0-9 、这三个字符".-_"组成。
# quorum 当这些quorum个数sentinel哨兵认为master主节点失联 那么这时 客观上认为主节点失联了
# sentinel monitor
sentinel monitor mymaster 127.0.0.1 6379 1
# 当在Redis实例中开启了requirepass foobared 授权密码 这样所有连接Redis实例的客户端都要提供密码
# 设置哨兵sentinel 连接主从的密码 注意必须为主从设置一样的验证密码
# sentinel auth-pass
sentinel auth-pass mymaster MySUPER--secret-0123passw0rd
# 指定多少毫秒之后 主节点没有应答哨兵sentinel 此时 哨兵主观上认为主节点下线 默认30秒
# sentinel down-after-milliseconds
sentinel down-after-milliseconds mymaster 30000
# 这个配置项指定了在发生failover主备切换时最多可以有多少个slave同时对新的master进行 同步,
这个数字越小,完成failover所需的时间就越长,
但是如果这个数字越大,就意味着越 多的slave因为replication而不可用。
可以通过将这个值设为 1 来保证每次只有一个slave 处于不能处理命令请求的状态。
# sentinel parallel-syncs
sentinel parallel-syncs mymaster 1
# 故障转移的超时时间 failover-timeout 可以用在以下这些方面:
#1. 同一个sentinel对同一个master两次failover之间的间隔时间。
#2. 当一个slave从一个错误的master那里同步数据开始计算时间。直到slave被纠正为向正确的master那里同步数据时。
#3.当想要取消一个正在进行的failover所需要的时间。
#4.当进行failover时,配置所有slaves指向新的master所需的最大时间。不过,即使过了这个超时,slaves依然会被正确配置为指向master,但是就不按parallel-syncs所配置的规则来了
# 默认三分钟
# sentinel failover-timeout
sentinel failover-timeout mymaster 180000
# SCRIPTS EXECUTION
#配置当某一事件发生时所需要执行的脚本,可以通过脚本来通知管理员,例如当系统运行不正常时发邮件通知相关人员。
#对于脚本的运行结果有以下规则:
#若脚本执行后返回1,那么该脚本稍后将会被再次执行,重复次数目前默认为10
#若脚本执行后返回2,或者比2更高的一个返回值,脚本将不会重复执行。
#如果脚本在执行过程中由于收到系统中断信号被终止了,则同返回值为1时的行为相同。
#一个脚本的最大执行时间为60s,如果超过这个时间,脚本将会被一个SIGKILL信号终止,之后重新执行。
#通知型脚本:当sentinel有任何警告级别的事件发生时(比如说redis实例的主观失效和客观失效等等),将会去调用这个脚本,
#这时这个脚本应该通过邮件,SMS等方式去通知系统管理员关于系统不正常运行的信息。调用该脚本时,将传给脚本两个参数,
#一个是事件的类型,
#一个是事件的描述。
#如果sentinel.conf配置文件中配置了这个脚本路径,那么必须保证这个脚本存在于这个路径,并且是可执行的,否则sentinel无法正常启动成功。
#通知脚本
# sentinel notification-script
sentinel notification-script mymaster /var/redis/notify.sh
# 客户端重新配置主节点参数脚本
# 当一个master由于failover而发生改变时,这个脚本将会被调用,通知相关的客户端关于master地址已经发生改变的信息。
# 以下参数将会在调用脚本时传给脚本:
#
# 目前总是“failover”,
# 是“leader”或者“observer”中的一个。
# 参数 from-ip, from-port, to-ip, to-port是用来和旧的master和新的master(即旧的slave)通信的
# 这个脚本应该是通用的,能被多次调用,不是针对性的。
# sentinel client-reconfig-script
sentinel client-reconfig-script mymaster /var/redis/reconfig.sh
布隆过滤器(重点)
缓存空对象
设置热点数据永不过期
加互斥锁(分布式锁)
redis高可用
限流降级
数据预热