redis/redis数据库缓存技术.md

689 lines
20 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<h1><center>Redis数据库缓存技术</center></h1>
------
## 一:缓存服务器简介
#### 1.简介
许多Web应用都将数据保存到 RDBMS关系数据库管理系统应用服务器从中读取数据并在浏览器中显示。但随着数据量的增大、访问的集中就会出现RDBMS的负担加重、数据库响应恶化、 网站显示延迟等重大影响。Memcached/redis是高性能的分布式内存缓存服务器,通过缓存数据库查询结果减少数据库访问次数以提高动态Web等应用的速度、 提高可扩展性。
#### 2.NoSql产品
产品: redis,mongodb,memcached
名词解释:非关系型数据库
以键值对的方式存储数据---Key-Value的形式
#### 3.NoSql的优点
高可扩展性
分布式计算
低成本
架构的灵活性,半结构化数据
没有复杂的关系
#### 4.NoSql的缺点
没有标准化
有限的查询功能
不直观的程序
#### 5.作用
加快访问速度 ,缓解数据库压力
注意:
非关系型数据库严格上不是一种数据库,应该是一种数据结构化存储方法的集合,可以是文档或者键值对等
## 二Redis基础
#### 1.简介
redis是一个开源的、使用C语言编写的、支持网络交互的、可基于内存也可持久化的Key-Value数据库
redis的官网redis.io 注:域名后缀io属于国家域名是british Indian Ocean territory即英属印度洋领地
#### 2.帮助
官方网站https://redis.io
官方各版本下载地址http://download.redis.io/releases/
Redis 中文命令参考http://redisdoc.com
中文网站1http://redis.cn
中文网站2http://www.redis.net.cn
#### 3.特点
丰富的数据结构 list,set,hash等数据结构的存储
支持持久化
支持事务 “一个完整的动作,要么全部执行,要么什么也没有做”
支持主从支持高可用,支持分布式分片集群
## 三Redis部署
#### 1.yum安装
安装仓库
```shell
[root@xingdian ~]# yum install http://rpms.famillecollet.com/enterprise/remi-release-7.rpm -y
```
安装redis
```shell
[root@xingdian ~]# yum --enablerepo=remi install redis -y
```
启动和开机启动
```shell
[root@xingdian ~]# systemctl start redis
[root@xingdian ~]# systemctl enable redis
```
设置redis.conf,允许远程登录
```shell
[root@xingdian ~]# vim /etc/redis.conf
bind 127.0.0.1 改为 bind 0.0.0.0 (可选)
```
登录
```shell
[root@xingdian ~]# systemctl restart redis
[root@xingdian ~]# redis-cli
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> set name xingdian
OK
127.0.0.1:6379> get name
"xingdian"
127.0.0.1:6379>
```
#### 2.编译安装
下载源码包
```shell
[root@xingdian ~]# wget https://download.redis.io/redis-stable.tar.gz
[root@xingdian ~]# tar xf redis-stable.tar.gz -C /usr/local/
```
安装编译所需软件
```shell
[root@xingdian ~]# yum install -y gcc-c++ autoconf automake make
```
编译
```shell
[root@xingdian redis-stable]# make
```
安装
```shell
[root@xingdian redis-stable]# make install
```
启动
```shell
[root@xingdian redis-stable]# cd src/
[root@xingdian src]# ./redis-server &
```
## 四Redis使用
#### 1.redis相关工具
```shell
./redis-benchmark #用于进行redis性能测试的工具
./redis-check-rdb #用于修复出问题的dump.rdb文件
./redis-cli #redis的客户端
./redis-server #redis的服务端
./redis-check-aof #用于修复出问题的AOF文件
./redis-sentinel #用于集群管理
```
#### 2.redis配置文件部分
```shell
1、是否后台运行
daemonize no/yes
2、默认端口
port 6379
3、AOF 日志开关是否打开
appendonly no/yes
4、日志文件位置
logfile /var/log/redis.log
5、RDB 持久化数据文件
dbfilename dump.rdb
6、指定IP进行监听
bind 10.0.0.51 ip2 ip3 ip4
7、禁止protected-mode
protected-mode yes/no (保护模式,是否只允许本地访问)
8、增加requirepass {password}
requirepass root9、在redis-cli中使用
```
#### 3.数据持久化
开启持久化功能后重启redis后数据会自动通过持久化文件恢复
redis提供了两种持久化的方式分别是RDBRedis DataBase和AOFAppend Only File仅追加文件
方式一RDB
RDBRedis DataBase是在不同的时间点将redis存储的数据生成快照并存储到磁盘等介质上
特点:
1.周期性
2.不影响数据写入 RDB会启动子进程备份所有数据。当前进程继续提供数据的读写。当备份完成才替换老的备份文件
3.高效;一次性还原所有数据
4.完整性较差 #故障点到上一次备份,之间的数据无法恢复
方式二AOF
AOFAppend Only File则是换了一个角度来实现持久化那就是将redis执行过的所有写指令记录下来在下次redis重新启动时只要把这些写指令从前到后再重复执行一遍就可以实现数据恢复了
特点:
1.实时性
2.完整性较好
3.体积大;记录数据的指令,删除数据的指令都会被记录下来
注意:
RDB和AOF两种方式可以同时使用如果redis重启的优先采用AOF方式进行数据恢复这是因为AOF方式的数据恢复完整度更高
如果你没有数据持久化的需求也完全可以关闭RDB和AOF方式这样的话redis将变成一个纯内存数据库就像memcache一样
如何选择:
缓存:不用开启任何持久方式
双开:因RDB数据不实时但同时使用两者时服务器只会找AOF文件,所以RDB留作万一的手段
对于我们应该选择RDB还是AOF官方的建议是两个同时使用。这样可以提供更可靠的持久化方案
写入速度快 ------------AOF
写入速度慢 ------------RDB
#### 4.持久化配置
1.RDB默认开启
```shell
[root@redis-master src]# cd ..
[root@redis-master redis]# vim redis.conf
#dbfilename持久化数据存储在本地的文件
dbfilename dump.rdb
#dir持久化数据存储在本地的路径
dir /data/application/redis/data
##snapshot触发的时机save <seconds> <changes>
##如下为900秒后至少有一个变更操作才会snapshot
##对于此值的设置,需要谨慎,评估系统的变更操作密集程度
##可以通过“save “””来关闭snapshot功能
#save时间以下分别表示更改了1个key时间隔900s进行持久化存储更改了10个key300s进行存储更改10000个key60s进行存储。
save 900 1
save 300 10
save 60 10000
##当snapshot时出现错误无法继续时是否阻塞客户端“变更操作”“错误”可能因为磁盘已满/磁盘故障/OS级别异常等
stop-writes-on-bgsave-error yes
##是否启用rdb文件压缩默认为“yes”压缩往往意味着“额外的cpu消耗”同时也意味这较小的文件尺寸以及较短的网络传输时间
rdbcompression yes
```
2.客户端使用命令进行持久化save存储
```shell
方式一
[root@redis-master src]# ./redis-cli -h 192.168.246.202 -p 6379 save #前台进行存储
OK
方式二
./redis-cli -h ip -p port bgsave #后台进行存储
```
3.AOF 持久化配置
```shell
appendonly yes/no 是否打开aof日志功能
appendfsync always 每1个命令,都立即同步到aof
appendfsync everysec 每秒写1次
appendfsync no 写入工作交给操作系统,由操作系统判断缓冲区大小,统一写入到aof.
高级参数:
no-appendfsync-on-rewrite yes/no 正在导出rdb快照的过程中,要不要停止同步 aof
auto-aof-rewrite-percentage 100 aof文件大小比起上次重写时的大小,增长率100%时重写,缺点:业务开始的时候,会重复重写多次。
auto-aof-rewrite-min-size 64mb aof文件,至少超过64M时,重写
```
4.RDB 到 AOF 切换
1、为最新的 dump.rdb 文件创建一个备份。
2、将备份放到一个安全的地方。
3、执行以下两条命令:
```shell
redis-cli config set appendonly yes
redis-cli config set save “”
```
4、确保写命令会被正确地追加到 AOF 文件的末尾
注意:
执行的第一条命令开启了 AOF 功能: Redis 会阻塞直到初始 AOF 文件创建完成为止, 之后 Redis 会继续处理命令请求, 并开始将写入命令追加到 AOF 文件末尾
执行的第二条命令用于关闭 RDB 功能。 这一步是可选的, 如果你愿意的话, 也可以同时使用 RDB 和 AOF 这两种持久化功能
别忘了在 redis.conf 中打开 AOF 功能! 否则的话, 服务器重启之后, 之前通过 CONFIG SET 设置的配置不会生效, 程序会按原来的配置来启动服务器
#### 5.数据恢复
将数据拷贝到另外一台新的服务器
先将新机器的redis停止,将数据拷贝到新机器定义的目录下,并覆盖原有的数据
```
[root@xingdian-server-12 ~]# systemctl start redis
[root@xingdian-server-12 ~]# redis-cli
127.0.0.1:6379> get diandian
"xingdian"
```
## 五Redis数据类型
#### 1.基本数据类型
| **类型** | **说明** |
| -------------------- | ------------------------------------------------------------ |
| String 字符串 | Redis 字符串数据类型的相关命令用于管理 redis 字符串值 |
| Hash 哈希 | Redis hash 是一个string类型的field和value的映射表hash特别适合用于存储对象。Redis 中每个 hash 可以存储 2的32次方2^32 - 1 键值对40多亿。 |
| List 列表 | Redis列表是简单的字符串列表按照插入顺序排序。你可以添加一个元素到列表的头部左边或者尾部右边 一个列表最多可以包含 2^32 - 1 个元素 (4294967295, 每个列表超过40亿个元素)。 |
| Set 集合 | Redis 的 Set 是 String 类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。 |
| Sorted set 有序集合 | Redis 有序集合和集合一样也是string类型元素的集合,且不允许重复的成员。 |
#### 2.Redis 命令介绍
```shell
127.0.0.1:6379> help
redis-cli 6.0.7
To get help about Redis commands type:
"help @<group>" to get a list of commands in <group>
"help <command>" for help on <command>
"help <tab>" to get a list of possible help topics
"quit" to exit
To set redis-cli preferences:
":set hints" enable online hints
":set nohints" disable online hints
Set your preferences in ~/.redisclirc
```
根据输出可以看到 help 命令有三种用法
```shell
“help @<group>” to get a list of commands in <group>,
”help <command>” for help on <command>,
”help <tab>” to get a list of possible help topics
```
**help @ 查看命令组的帮助**
help [@generic](https://my.oschina.net/generic) 查看通用组的命令包括deldump…等等通用命令
help [@string](https://my.oschina.net/u/146445) 查看字符串组命令。还可以查看其他组的命令如help [@list](https://my.oschina.net/u/587374) help [@set](https://my.oschina.net/rosetta), help @sorted_set,help @hash 等等
查看所有的分组可以通过help <tab>提示
```
127.0.0.1:6379> help @generic
DEL key [key ...]
summary: Delete a key
since: 1.0.0
DUMP key
summary: Return a serialized version of the value stored at the specified key.
since: 2.6.0
EXISTS key [key ...]
summary: Determine if a key exists
since: 1.0.0
EXPIRE key seconds
summary: Set a key's time to live in seconds
since: 1.0.0
EXPIREAT key timestamp
summary: Set the expiration for a key as a UNIX timestamp
since: 1.2.0
KEYS pattern
summary: Find all keys matching the given pattern
since: 1.0.0
MIGRATE host port key| destination-db timeout [COPY] [REPLACE] [AUTH password] [KEYS key]
summary: Atomically transfer a key from a Redis instance to another one.
since: 2.6.0
MOVE key db
summary: Move a key to another database
since: 1.0.0
OBJECT subcommand [arguments [arguments ...]]
summary: Inspect the internals of Redis objects
since: 2.2.3
PERSIST key
summary: Remove the expiration from a key
since: 2.2.0
PEXPIRE key milliseconds
summary: Set a key's time to live in milliseconds
since: 2.6.0
PEXPIREAT key milliseconds-timestamp
summary: Set the expiration for a key as a UNIX timestamp specified in milliseconds
since: 2.6.0
PTTL key
summary: Get the time to live for a key in milliseconds
since: 2.6.0
RANDOMKEY -
summary: Return a random key from the keyspace
since: 1.0.0
RENAME key newkey
summary: Rename a key
since: 1.0.0
RENAMENX key newkey
summary: Rename a key, only if the new key does not exist
since: 1.0.0
RESTORE key ttl serialized-value [REPLACE] [ABSTTL] [IDLETIME seconds] [FREQ frequency]
summary: Create a key using the provided serialized value, previously obtained using DUMP.
since: 2.6.0
SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]
summary: Incrementally iterate the keys space
since: 2.8.0
SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]
summary: Sort the elements in a list, set or sorted set
since: 1.0.0
TOUCH key [key ...]
summary: Alters the last access time of a key(s). Returns the number of existing keys specified.
since: 3.2.1
TTL key
summary: Get the time to live for a key
since: 1.0.0
TYPE key
summary: Determine the type stored at key
since: 1.0.0
UNLINK key [key ...]
summary: Delete a key asynchronously in another thread. Otherwise it is just as DEL, but non blocking.
since: 4.0.0
WAIT numreplicas timeout
summary: Wait for the synchronous replication of all the write commands sent in the context of the current connection
since: 3.0.0
GEORADIUSBYMEMBER_RO key arg arg arg ...options...
summary: Help not available
since: not known
SUBSTR key arg arg
summary: Help not available
since: not known
PFDEBUG arg arg ...options...
summary: Help not available
since: not known
BITFIELD_RO key ...options...
summary: Help not available
since: not known
HOST: ...options...
summary: Help not available
since: not known
XSETID key arg
summary: Help not available
since: not known
ASKING
summary: Help not available
since: not known
GEORADIUS_RO key arg arg arg arg ...options...
summary: Help not available
since: not known
REPLCONF ...options...
summary: Help not available
since: not known
PFSELFTEST
summary: Help not available
since: not known
RESTORE-ASKING key arg arg ...options...
summary: Help not available
since: not known
POST ...options...
summary: Help not available
since: not known
```
**help 查看具体命令的用法**
help 具体命令可以查看命令的用法描述,命令从那个版本开始,命令属于哪个组等信息。如 help get
```shell
127.0.0.1:6379> help get
GET key
summary: Get the value of a key
since: 1.0.0
group: string
```
**help help后面参数提示补全**
help 之后按tab按键可提示参数。在命令行下 tab按键相信是用的最多的一个按键
help 空格之后一直按tab,可按顺序查看到所有可能的组和命令。也可输入需要查询的@组或命令的前缀再按tab补全
#### 3.Redis 全局 Key 操作
| **命令** | **含义** |
| --------------- | --------------------------- |
| KEYS * | 查看KEY支持通配符 |
| DEL | 删除给定的一个或多个key |
| EXISTS | 检查是否存在 |
| RENAME | 变更KEY名 |
| SORT | 键值排序,有非数字时报错 |
| TYPE | 返回键所存储值的类型 |
| DUMP RESTORE | 序例化与反序列化 |
| EXPIRE\ PEXPIRE | 以秒\毫秒设定生存时间 |
| TTL\ PTTL | 以秒\毫秒为单位返回生存时间 |
| PERSIST | 取消生时间设置 |
| RANDOMKEY | 返回数据库中的任意键 |
1、del 命令
del 命令用来 删除指定的一个或多个 key
删除一个 key
```shell
127.0.0.1:6379> set test 1234
127.0.0.1:6379> del test
```
删除多个 key
```shell
127.0.0.1:6379> mset test1 1111 test2 2222
127.0.0.1:6379> del test1 test2
```
2、exists 命令
exists 命令用来查询 key 是否存在
```shell
127.0.0.1:6379> mset test1 1111 test2 2222
192.168.152.133:6379> EXISTS test1
(integer) 1
```
3、expire 命令
expire 命令用来 设置 key 的过期秒数
```shell
127.0.0.1:6379> get test1
```
与 expire 命令相关的命令有三个,分别是:
expireat 命令用来 设置一个 UNIX 时间戳的过期时间, 从1970年1月1日0时0分0秒到你设置过期的秒数
```shell
127.0.0.1:6379> EXPIREAT test2 1592965943
(integer) 1
```
pexpire 命令用来 设置 key 的有效时间以毫秒为单位
```shell
127.0.0.1:6379> EXPIRE test3 100
(integer) 1
127.0.0.1:6379> ttl test3
(integer) 94
127.0.0.1:6379> pttl test3
(integer) 89235
```
pexpireat 命令用来 设置 key 的到期 UNIX 时间戳以毫秒为单位
```shell
127.0.0.1:6379> PEXPIREAT test3 1592965943000
(integer) 1
192.168.152.133:6379> ttl test3
(integer) 365
```
4、keys 命令
keys 命令用来 查找所有匹配给定的模式的键
```shell
127.0.0.1:6379> keys *
1) "a"
2) "test"
3) "test1"
4) "name"
```
在 Redis 中是支持模糊查询的,它有 3 个通配符,分别是:*、 ? 和 []
*:通配任意多个字符
?:通配单个字符
[]:通配括号内的某 1 个字符
[] 的用法如下:
```shell
127.0.0.1:6379> keys *[s]*
1) "test"
2) "test1"
127.0.0.1:6379> keys *[a]*
1) "a"
2) "name"
```
? 的用法如下:
```shell
127.0.0.1:6379> set a bbb
OK
127.0.0.1:6379> keys ?
1) "a"
```
5.ttl 命令
ttl 命令用来 获取 key 的有效时间(单位:秒)
```shell
127.0.0.1:6379> get test1
```
上面的命令是,我们用 expire 对一个 key 设置一个过期时间,然后使用 ttl 观察它的剩余时间
ttl 一个 key如果返回 -1则说明该 key 不会过期
ttl 一个 key如果返回 -2则说明没有指定的 key
与 ttl 相关的命令是 pttl 命令,它用来 获取 key 的有效毫秒数
#### 4.数据类型
string是redis最基本的类型一个key对应一个value。一个键最大能存储 512MB
Redis中的Hashes类型看成具有String Key和String Value的map容器所以该类型非常适合于存储值对象的信息。如Username、Password和Age等。如果Hash中包含很少的字段那么该类型的数据也将仅占用很少的磁盘空间。每一个Hash可以存储995701749 个键值对
List类型是按照插入顺序排序的字符串链表。和数据结构中的普通链表一样我们可以在其头部(left)和尾部(right)添加新的元素
Set类型看作为没有排序的字符集合。Set可包含的最大元素数量是4294967295
Sorted-Sets中的每一个成员都会有一个分数(score)与之关联Redis正是通过分数来为集合中的成员进行从小到大的排序。成员是唯一的但是分数(score)却是可以重复的
扩展链接地址https://docs.qq.com/doc/DQ0ZIQ0l4eWRkdm1J