CentOS 7.6 redis数据库的安装配置及常用数据库命令

Redis 数据库是一个非关系型数据库

一、非关系型数据库

NoSQL(NoSQL = Not Only SQL ),意思是“不仅仅是 SQL”,是非关系型数据库的总称。 主流的 NoSQL 数据库有 Redis、MongBD、Hbase、CouhDB 等等。以上这些非关系型数 据库,他们的存储方式、存储结构以及使用的场景都是完全不同的。所以我们认为它是一个 非关系型数据库的集合,而不是像关系型数据库一样,是一个统称。换言之,除了主流的关 系型数据库以外的数据库,都可以认为是非关系型的。NoSQL 数据库凭借着其非关系型、 分布式、开源及横向扩展等优势,被认为是下一代数据库产品

二、Redis简介

Redis(RemoteDictionaryServer,远程字典型)是一个开源的、使用 C 语言编写的NoSQL 数据库。Redis 基于内存运行并支持持久化,采用 key-value(键值对)的存储形式, 是目前分布式架构中不可或缺的一环。 Redis服务器程序是单进程模型,也就是在一台服务器上可以同时启动多个Redis进程, 而 Redis 的实际处理速度则是完全依靠于主进程的执行效率。若在服务器上只运行一个 Redis 进程,当多个客户端同时访问时,服务器的处理能力是会有一定程度的下降;若在同 一台服务器上开启多个 Redis 进程,Redis 在提高并发处理能力的同时会给服务器的 CPU 造成很大压力。

1、Redis 优点

  • 具有极高的数据读写速度,数据读取的速度最高可达到 110000 次/s,数据写入速度最 高可达到 81000 次/s
  • 支持丰富的数据类型,不仅仅支持简单的 key-value 类型的数据,还支持 Strings, Lists, Hashes, Sets 及Ordered Sets 等数据类型操作
  • 支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
  • 原子性,Redis 所有操作都是原子性的。
  • 支持数据备份,即 master-salve 模式的数据备份。

Redis 作为基于内存运行的数据库,缓存是其最常应用的场景之一。除此之外,Redis 常见应用场景还包括获取最新 N 个数据的操作、排行榜类应用、计数器应用、存储关系、 实时分析系统、日志记录

三、Redis 安装部署

首先需要安装编译工具

[root@redis ~]# yum -y install gcc gcc-c++ make

解压redis的tar包到/opt下

[root@redis ~]# cd /opt
[root@redis opt]# tar xzvf redis-5.0.7.tar.gz 

编译安装

[root@redis opt]# cd redis-5.0.7/
[root@redis opt]# make
[root@redis redis-5.0.7]# make PREFIX=/usr/local/redis install  <---如果不指定,默认会在此目录下有一个redis.conf文件就是他的默认配置文件

make install 只是安装了二进制文件到系统中,并没有启动脚本和配置文件。软件包中默认提供了一个 install_server.sh 脚本文件,通过该脚本文件可以设置 Redis 服务所需要的 相关配置文件。当脚本运行完毕,Redis 服务就已经启动,默认侦听端口为 6379。

[root@redis redis-5.0.7]# cd /opt/redis-5.0.7/utils/
[root@redis utils]# ./install_server.sh
Welcome to the redis service installer
This script will help you easily set up a running redis server

Please select the redis port for this instance: [6379] <---回车
Selecting default: 6379
Please select the redis config file name [/etc/redis/6379.conf] <---回车
Selected default - /etc/redis/6379.conf
Please select the redis log file name [/var/log/redis_6379.log] <---回车
Selected default - /var/log/redis_6379.log
Please select the data directory for this instance [/var/lib/redis/6379] <---回车
Selected default - /var/lib/redis/6379
Please select the redis executable path [] /usr/local/redis/bin/redis-server  //需要手动指定
Selected config:
Port           : 6379
Config file    : /etc/redis/6379.conf  <----配置文件路径
Log file       : /var/log/redis_6379.log    <----日志文件路径
Data dir       : /var/lib/redis/6379   <----数据文件路径
Executable     : /usr/local/redis/bin/redis-server   <----可执行文件路径
Cli Executable : /usr/local/redis/bin/redis-cli   <----客户端命令行工具
Is this ok? Then press ENTER to go on or Ctrl-C to abort.
Copied /tmp/6379.conf => /etc/init.d/redis_6379
Installing service...
Successfully added to chkconfig!
Successfully added to runlevels 345!
Starting Redis server...
Installation successful!

为命令创建软链接方便使用

[root@redis redis-5.0.7]# ln -s /usr/local/redis/bin/* /usr/local/bin

查看启动状态

[root@redis utils]# netstat -anpt | grep 6379
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      106064/redis-server
[root@redis utils]# ps -ef | grep redis
root     108304      1  0 18:57 ?        00:00:00 redis-server *:6379
root     108310 101574  0 18:57 pts/2    00:00:00 redis-cli -h 192.168.245.204

四、redis的启动和关闭

1、启动redis

1[root@redis utils]# redis-server(默认会把log打印在前台,效果如图,修改配置文件里的daemonize为yes,前台就不显示信息了)

在这里插入图片描述

2[root@redis utils]# redis-server --port 6379  <---在启动多实例的情况下可以使用这种方式
   [root@redis utils]# redis-server --port 6380
3[root@redis utils]# redis-server /etc/redis/6379.conf   <---指定配置文件的方式,常用于多实例
4[root@redis utils]# /etc/init.d/redis_6379 start  <---软启动,最常用
Starting Redis server...

2、停止redis

1[root@redis utils]# redis-server    <----如果是log显示在前台的情况
   ctrl+c(立即停止)

^C107605:signal-handler (1599818059) Received SIGINT scheduling shutdown...
107605:M 11 Sep 2020 17:54:19.067 # User requested shutdown...
107605:M 11 Sep 2020 17:54:19.067 * Saving the final RDB snapshot before exiting.
107605:M 11 Sep 2020 17:54:19.068 * DB saved on disk
107605:M 11 Sep 2020 17:54:19.068 # Redis is now ready to exit, bye bye...
2[root@redis utils]# redis-cli shutdown   <---使用客户端连接工具也可以
3[root@redis utils]# /etc/init.d/redis_6379 stop   <----常用方式
Stopping ...
Redis stopped
4[root@redis utils]# kill -9 [进程号]     <----以上方式都不能关闭的情况可以直接杀死进程

3、重启redis

[root@redis utils]# /etc/init.d/redis_6379 restart   <---重启服务
Stopping ...
Redis stopped
Starting Redis server...

4、查看redis状态

[root@redis utils]# /etc/init.d/redis_6379 status
Redis is running (108549)

五、客户端连接

redis-cli 命令行工具 Redis 数据库系统也是一个典型的 C/S(客户端/服务器端)架构的应用,要访问 Redis 数据库需要使用专门的客户端软件。Redis 服务的客户端软件就是其自带的 redis-cli 命令行工具。使用 redis-cli 连接指定数据库,连接成功后用户可以输入各种操作语句对数据库进行管理

直接使用redis-cli命令,默认连接到本地的redis,端口为6379的实例

[root@redis ~]# redis-cli
127.0.0.1:6379> 

如果存在多个实例可以-p带端口号,注意-p后面有空格

[root@redis ~]# redis-cli -p 6379
127.0.0.1:6379> 

如果要连接到其他的redis服务器实例,要用-h参数,默认只能连本地

[root@redis ~]# redis-cli -h 127.0.0.1 -p 6379
127.0.0.1:6379>
[root@redis ~]# redis-cli -h 192.168.245.204
192.168.245.204:6379> keys *
(error) DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.

注意,如果你想让任何人都能访问你,需要在配置文件里把bind注释,protected-mode改为no,然后重启服务才行,否则默认只能连本地的redis

如果是redis-server方式启动的话,后面需要跟配置文件否则不能生效
[root@redis utils]# redis-server /etc/redis/6379.conf

如果要在windows系统中远程到redis服务器可以下载客户端连接工具

客户端连接工具(图形化界面操作):redis desktop manager(windows)

六、配置文件解读

Redis 主配置文件为/etc/redis/6379.conf,由注释行与设置行两部分组成。与大多数 Linux 配置文件一样,注释性的文字以“#”开始,包含了对相关配置内容进行的说明和解释。 除了注释行与空行以外的内容即为设置行。可根据生产环境的需求调整相关参数

[root@redis utils]# vim /etc/redis/6379.conf
bind 127.0.0.1 192.168.245.204     <---监听的主机地址,多个用空格分开
port 6379       <---端口号
daemonize yes        <---启用守护进程 
pidfile /var/run/redis_6379.pid        <---指定PID文件 
loglevel notice         <---日志级别 
logfile /var/log/redis_6379.log      <---指定日志文件
dbfilename dump.rdb   <---指定rdb持久化文件名,默认值为dump.rdb
dir /var/lib/redis/6379   <---指定本地数据库存放目录
rdbcompression yes    <---指定存储至本地数据库时是否压缩数据,默认为 yes
appendonly no    <---是否开启aof持久化,Redis在默认情况下是异步地把数据写入磁盘,如果不开启, 可能会在断电时导致一段时间内的数据丢失
appendfilename appendonly.aof   <---指定aof文件名,默认为appendonly.aof
appendfsync everysec   <---指定aof持久化触发条件

七、数据库操作

首先连接到数据库

[root@redis ~]# redis-cli
127.0.0.1:6379> 

检测 redis 服务是否启动

127.0.0.1:6379> ping
PONG

查看当前数据库实例的信息

127.0.0.1:6379> info
# Server
redis_version:5.0.7
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:22935f49bf15c567
……省略部分内容

# Clients
connected_clients:1
client_recent_max_input_buffer:2
client_recent_max_output_buffer:0
blocked_clients:0

# Memory
used_memory:854280
……省略部分内容

# Persistence
loading:0
……省略部分内容

# Stats
total_connections_received:4
……省略部分内容

# Replication
role:master
……省略部分内容

# CPU
used_cpu_sys:0.749002
……省略部分内容

# Cluster
cluster_enabled:0

# Keyspace

查看帮助信息

127.0.0.1:6379> help
redis-cli 5.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

使用quit或exit退出数据库

127.0.0.1:6379> quit
[root@redis ~]# 

八、常用命令

前面提到 Redis 数据库采用 key-value(键值对)的数据存储形式。所使用的命令是 set 与 get 命令。

  • set:存放数据,基本的命令格式为 set key value。

  • get:获取数据,基本的命令格式为 get key。

例如:定义一个key叫teacher,值为chenyan

127.0.0.1:6379> set teacher chenyan
OK
127.0.0.1:6379> get teacher
"chenyan"

非常人性化的一点是,你输入命令之后,后面会有阴影部分告诉你怎么用,如图
在这里插入图片描述
而且命令可以使用tab键补全

1、key命令

使用 keys 命令可以取符合规则的键值列表,通常情况可以结合*、?等选项来使用
* 代表任意多的字符
? 代表任意一个字符

127.0.0.1:6379> set stu1 shengjie
OK
127.0.0.1:6379> set stu2 tangyan
OK
127.0.0.1:6379> set stu3 shangzhen
OK
127.0.0.1:6379> set stu4 zhaokun
OK
127.0.0.1:6379> keys *   <----查看当前数据库中所有键
1) "stu2"
2) "stu4"
3) "teacher"
4) "stu3"
5) "stu1"

查看所有以s开头的键

127.0.0.1:6379> keys s*
1) "stu2"
2) "stu4"
3) "stu3"
4) "stu1"

查看以s开头后面3个字符的键

127.0.0.1:6379> keys s???
1) "stu2"
2) "stu4"
3) "stu3"
4) "stu1"
127.0.0.1:6379> keys *2
1) "stu2"
127.0.0.1:6379> keys ???2
1) "stu2"

2、exists

exists 命令可以判断键值是否存在,存在返回1,不存在返回0

127.0.0.1:6379> EXISTS teacher
(integer) 1
127.0.0.1:6379> EXISTS teacher1
(integer) 0

3、del

del 命令可以删除当前数据库的指定 key。

删除stu3键

127.0.0.1:6379> del stu3
(integer) 1
127.0.0.1:6379> get stu3
(nil)

可以同时删除多个键

127.0.0.1:6379> del key stu1 stu2
(integer) 2    <----执行了2个操作,所以返回值是2
127.0.0.1:6379> keys *
1) "stu4"
2) "teacher"

4、type

使用 type 命令可以获取 key 对应的 value 值类型。

127.0.0.1:6379> type teacher
string

5、rename

rename 命令是对已有 key 进行重命名,其命令格式为:rename 源 key 目标 key。
使用 rename 命令进行重命名时,无论目标 key 是否存在都进行重命名,且源 key 的值会覆盖目标 key 的值。在实际使用过程中,建议先用 exists 命令查看目标 key 是否存在,然后再决定是否执行 rename 命令,以避免覆盖重要数据。

127.0.0.1:6379> rename stu4 student4
OK
127.0.0.1:6379> keys *
1) "teacher"
2) "student4"

6、renamenx

renamenx 命令的作用是对已有 key 进行重命名,并检测新名是否存在。其命令格式与 rename 的命令格式除命令关键字不同外基本相同:renamenx 源 key 目标 key。
使用 renamenx 命令进行重命名时,如果目标 key 存在则不进行重命名。

127.0.0.1:6379> set student chengu   <---新添加一个键为student,值为chengu
OK
127.0.0.1:6379> keys *
1) "student"
2) "teacher"
3) "student4"

127.0.0.1:6379> renamenx student4 student  <---将student4改名为student,因为student已存在所以改名失败
(integer) 0
127.0.0.1:6379> keys *
1) "student"
2) "teacher"
3) "student4"
127.0.0.1:6379> renamenx student4 student1  <---将student4改名为student1,因为student1原本不存在,所以改名成功
(integer) 1
127.0.0.1:6379> keys *
1) "student1"
2) "student"
3) "teacher"

7、dbsize

dbsize 命令的作用是查看当前数据库中 key 的数目。

127.0.0.1:6379> keys *
1) "student1"
2) "student"
3) "teacher"
127.0.0.1:6379> DBSIZE  <---自动补全的命令默认是大写的
(integer) 3

8、多数据库间切换

Redis 支持多数据库,Redis 在没有任何改动的情况下默认包含 16 个数据库,数据库名称是用数字 0-15 来依次命名的。使用 select 命令可以进行 Redis 的多数据库之间的切换, 命令格式为 select index,其中 index 表示数据库的序号。而使用 redis-cli 连接 Redis 数据库后,默认使用的是序号为 0 的数据库。

127.0.0.1:6379> SELECT 2
OK
127.0.0.1:6379[2]> keys *
(empty list or set)
127.0.0.1:6379[2]> 
127.0.0.1:6379[2]> set hobby game
OK
127.0.0.1:6379[2]> get hobby
"game"
127.0.0.1:6379[2]> keys *
1) "hobby"
127.0.0.1:6379[2]> SELECT 0
OK
127.0.0.1:6379> 

9、多数据库间移动

Redis 的多数据库在一定程度上是相对独立的,例如在数据库 0 上面存放的数据, 在其它 1-15 的数据库上是无法查看到的
Redis 数据库提供了一个 move 的命令,可以进行多数据库之间的数据移动。
命令的基本语法格式为“move key dbindex”。其中“key”表示当前数据库的目标键,“dbindex”表示目标数据库的序号

127.0.0.1:6379> move teacher 2
(integer) 1
127.0.0.1:6379> keys *
1) "student1"
2) "student"
127.0.0.1:6379> select 2
OK
127.0.0.1:6379[2]> keys *
1) "hobby"
2) "teacher"
127.0.0.1:6379[2]> get teacher
"chenyan"
127.0.0.1:6379[2]> 

10、清除数据库内数据

Redis数据库的整库数据删除主要分为两个部分:
清空当前数据库数据,使用 FLUSHDB 命令实现
清空所有数据库的数据,使用 FLUSHALL 命令实现,这里不演示了
但是,数据清空操作比较危险,生产环境下一般不建议使用

127.0.0.1:6379[2]> keys *
1) "hobby"
2) "teacher"
127.0.0.1:6379[2]> FLUSHdb
OK
127.0.0.1:6379[2]> keys *
(empty list or set)

11、monitor 实时监控

又打开了一个新的终端,输入如下命令

[root@redis ~]# redis-cli
127.0.0.1:6379> keys *
1) "student1"
2) "student"
127.0.0.1:6379> get student
"chengu"

原来的终端上开了实时监控,所以所有操作都记录了下来,ctrl+c退出监控

127.0.0.1:6379> MONITOR
OK
1599843696.932933 [0 127.0.0.1:60210] "COMMAND"
1599843706.213384 [0 127.0.0.1:60210] "keys" "*"
1599843714.771721 [0 127.0.0.1:60210] "get" "student"

九、常用存储结构

  • key-string:一个key对应一个值,存储一个值
  • key-hash:一个key对应一个map,存储一个对象
  • key-list:一个key对应一个列表(有序允许重复)
  • key-set:一个key对应一个集合(无序不允许重复)
  • key-zset:一个key对应一个有序的集合(有序不允许重复)

hash结构存数据方式

存入一个person对象,键有name,age,address,birthday

127.0.0.1:6379> hset person name zhangsan
(integer) 1
127.0.0.1:6379> hset person age 23
(integer) 1
127.0.0.1:6379> hset person address nanjing
(integer) 1
127.0.0.1:6379> hset person birthday 8.8
(integer) 1
127.0.0.1:6379> type person    <-----查看类型为hash
hash
127.0.0.1:6379> hget person name
"zhangsan"

取出所有键值

127.0.0.1:6379> HGETALL person
1) "name"
2) "zhangsan"
3) "age"
4) "23"
5) "address"
6) "nanjing"
7) "birthday"
8) "8.8"

取出所有键

127.0.0.1:6379> hkeys person
1) "name"
2) "age"
3) "address"
4) "birthday"

取出所有值

127.0.0.1:6379> hvals person
1) "zhangsan"
2) "23"
3) "nanjing"
4) "8.8"

查询person的长度

127.0.0.1:6379> hlen person
(integer) 4

批量存取

127.0.0.1:6379> mset gender man birthday 2000-01-01
OK
127.0.0.1:6379> keys *
1) "student1"
2) "birthday"
3) "student"
4) "person"
5) "gender"
127.0.0.1:6379> mget gender birthday
1) "man"
2) "2000-01-01"

自增自减

127.0.0.1:6379> set age 10
OK
127.0.0.1:6379> get age
"10"
127.0.0.1:6379> incr age
(integer) 11
127.0.0.1:6379> get age
"11"
127.0.0.1:6379> decr age
(integer) 10
127.0.0.1:6379> get age
"10"

指定自增的数量

127.0.0.1:6379> incrby age 5
(integer) 15
127.0.0.1:6379> get age
"15"

setex xxx 5 yyy 设定只存在5秒,生存时间,5秒以后查询不到xxx的值

127.0.0.1:6379> setex score 5 '80'
OK
127.0.0.1:6379> get score
"80"
127.0.0.1:6379> get score
"80"
127.0.0.1:6379> get score
"80"
127.0.0.1:6379> get score
(nil)

九、redis-benchmark压测

redis-benchmark 是官方自带的 Redis 性能测试工具,可以有效的测试 Redis 服务的性能。基本的测试语法为 redis-benchmark [option] [option value]。

常用选项如下所示

-h:指定服务器主机名;
-p:指定服务器端口;
-s:指定服务器 socket; 
-c:指定并发连接数;
-n:指定请求数;
-d:以字节的形式指定 SET/GET 值的数据大小;
-k:1=keep alive 0=reconnect; 
-r:SET/GET/INCR 使用随机 key, SADD 使用随机值;
-P:通过管道传输<numreq>请求; 
-q:强制退出 redis。仅显示 query/sec 值; 
--csv:以 CSV 格式输出;
-l:生成循环,永久执行测试; 
-t:仅运行以逗号分隔的测试命令列表;
-I:Idle 模式。仅打开 N 个 idle 连接并等待。

指定10万个连接,并发连接为100,测试各操作的性能

[root@redis ~]# redis-benchmark -c 100 -n 100000
====== PING_INLINE ======
  100000 requests completed in 1.91 seconds
  100 parallel clients
  3 bytes payload
  keep alive: 1

75.43% <= 1 milliseconds
91.57% <= 2 milliseconds
97.53% <= 3 milliseconds
99.20% <= 4 milliseconds
99.67% <= 5 milliseconds
99.78% <= 6 milliseconds
99.90% <= 7 milliseconds
99.99% <= 8 milliseconds
100.00% <= 10 milliseconds
100.00% <= 10 milliseconds
52383.45 requests per second

====== PING_BULK ======
  100000 requests completed in 4.22 seconds
  100 parallel clients
  3 bytes payload
  keep alive: 1

……省略部分内容
23685.46 requests per second

====== SET ======
  100000 requests completed in 4.07 seconds
  100 parallel clients
  3 bytes payload
  keep alive: 1

……省略部分内容
24582.11 requests per second
……省略部分内容

测试存取大小为 100 字节的数据包的性能

[root@redis ~]# redis-benchmark -q -d 100
PING_INLINE: 40816.32 requests per second
PING_BULK: 17655.37 requests per second
SET: 16966.41 requests per second
GET: 18772.29 requests per second
INCR: 18416.21 requests per second
LPUSH: 20048.12 requests per second
RPUSH: 18821.76 requests per second
LPOP: 18063.58 requests per second
RPOP: 18758.21 requests per second
SADD: 17488.63 requests per second
HSET: 18066.85 requests per second
SPOP: 18142.23 requests per second
LPUSH (needed to benchmark LRANGE): 17412.50 requests per second
LRANGE_100 (first 100 elements): 9804.88 requests per second
LRANGE_300 (first 300 elements): 5057.15 requests per second
LRANGE_500 (first 450 elements): 3516.79 requests per second
LRANGE_600 (first 600 elements): 2634.49 requests per second
MSET (10 keys): 17577.78 requests per second

猜你喜欢

转载自blog.csdn.net/shengjie87/article/details/108500696