Redis安装与使用

1.Redis介绍

Redis是一种高级key-value数据库。它跟memcached类似,不过数据可以持久化,而且支持的数据类型很丰富。有字符串,链表、哈希、集合和有序集合5种。支持在服务器端计算集合的并、交和补集(difference)等,还支持多种排序功能。所以Redis也可以被看成是一个数据结构服务器。Redis的所有数据都是保存在内存中,然后不定期的通过异步方式保存到磁盘上(这称为“半持久化模式”);也可以把每一次数据变化都写入到一个append only file(aof)里面(这称为“全持久化模式”)。

2.Redis安装

2.1下载Redis压缩包

下载地址:https://redis.io/download

2.2Redis解压与安装

1.解压:redis-6.2.6.tar.gz

查看代码
cd /software/redis/

tar -xzf redis-6.2.6.tar.gz

解压之后的文件:

查看代码
-rw-rw-r--  1 root root 33624 10月  4 18:59 00-RELEASENOTES
-rw-rw-r--  1 root root    51 10月  4 18:59 BUGS
-rw-rw-r--  1 root root  5026 10月  4 18:59 CONDUCT
-rw-rw-r--  1 root root  3384 10月  4 18:59 CONTRIBUTING
-rw-rw-r--  1 root root  1487 10月  4 18:59 COPYING
drwxrwxr-x  7 root root  4096 3月   2 21:09 deps
-rw-rw-r--  1 root root    11 10月  4 18:59 INSTALL
-rw-rw-r--  1 root root   151 10月  4 18:59 Makefile
-rw-rw-r--  1 root root  6888 10月  4 18:59 MANIFESTO
-rw-rw-r--  1 root root 21567 10月  4 18:59 README.md
-rw-rw-r--  1 root root 93724 3月   2 22:04 redis.conf
-rwxrwxr-x  1 root root   275 10月  4 18:59 runtest
-rwxrwxr-x  1 root root   279 10月  4 18:59 runtest-cluster
-rwxrwxr-x  1 root root  1079 10月  4 18:59 runtest-moduleapi
-rwxrwxr-x  1 root root   281 10月  4 18:59 runtest-sentinel
-rw-rw-r--  1 root root 13768 10月  4 18:59 sentinel.conf
drwxrwxr-x  3 root root 12288 3月   2 21:11 src
drwxrwxr-x 11 root root  4096 10月  4 18:59 tests
-rw-rw-r--  1 root root  3055 10月  4 18:59 TLS.md
drwxrwxr-x  9 root root  4096 10月  4 18:59 utils

2.编译:make

查看代码
cd redis-6.2.6
make

make命令执行完之后,会在redis.6.2.6/src 目录下生成几个可执行文件:

  1. redis-server:Redis服务器

  2. reids-cli:Redis客户端,Redis命令执行工具

  3. redis-benchmark:Redis性能测试工具,也可以用telent根据纯文本协议来操作

  4. redis-check-aof:数据修复

  5. reids-check-dump:检查导出工具

注:由于src下生成文件较多,查找文件不便,可将redis关键文件复制到redis.6.2.6目录下(自定义目录),如下所示:

3.安装

指定安装位置

查看代码
mkdir ~/software/redis-bin
make install PREFIX=~/software/redis-bin/   #PREFIX选项用来指定安装的位置

 

不指定安装位置,直接在当前解压目录下面执行:make install ,默认安装位置为:/usr/local/bin

[root redis-6.2.7]# make install
cd src && make install
make[1]: 进入目录“/root/software/redis/redis-6.2.7/src”
    CC Makefile.dep
make[1]: 离开目录“/root/software/redis/redis-6.2.7/src”
make[1]: 进入目录“/root/software/redis/redis-6.2.7/src”

Hint: It's a good idea to run 'make test' ;)

    INSTALL redis-server
    INSTALL redis-benchmark
    INSTALL redis-cli
make[1]: 离开目录“/root/software/redis/redis-6.2.7/src”
[root redis-6.2.7]# cd /usr/local/bin/
[root redis-6.2.7]# ls
chardetect  cloud-init      easy_install      easy_install-3.8  jsonpatch    jsonschema       redis-check-aof  redis-cli       redis-server
cloud-id    cloud-init-per  easy_install-3.6  jsondiff          jsonpointer  redis-benchmark  redis-check-rdb  redis-sentinel

 

 

2.3启动Redis服务器和Redis客户端

启动Redis服务器:

进入redis.6.2.6/src 目录下执行命令:

默认配置文件启动:./redis-server

指定配置文件启动:./reids-server /redis.conf配置文件所在目录

 

启动Redis客户端:

进入redis.6.2.6/src 目录下执行命令:

  • ./reids-cli (-h:默认127.0.0.1 或 localhost,-p:6379)

  • ./redis­cli ­-h IP地址 ­-p 端口号  #连接指定主机、指定端口的redis,如./redis­cli ­h localhost ­p 6379

当Reids服务器设置密码时(requirepass password),Reids客户端启动命令:./redis-cli -h ip -p port(默认6379) -a password

 

补充:可将 ../software/redis-bin/ 添加到PATH变量中,便于执行命令

查看代码
vi ~/.bashrc
export PATH=$PATH:/Users/wangbo/software/redis­bin/bin
    
source ~/.bashrc

2.4停掉Redis服务:shutdown命令或者kill -9 pid

[root bin]# redis-cli 
127.0.0.1:6379> set redis redis
OK
127.0.0.1:6379> get redis
"redis"
127.0.0.1:6379> get redis2
(nil)
127.0.0.1:6379> shutdown
not connected> exit
[root bin]# ps -ef | grep redis
root     24098 25746  0 00:02 pts/0    00:00:00 grep --color=auto redis

 

3.修改系统配置文件

1. echo overcommit_memory=1 >> /etc/sysctl.conf

2.  sysctl vm.overcommit_memory=1

     或执行echo vm.overcommit_memory=1 >>/proc/sys/vm/overcommit_memory

使用数字含义:

0:表示内核将检查是否有足够的可用内存供应用进程使用;如果有足够的可用内存,内存申请允许;否则,内存申请失败,并把错误返回给应用进程。

1:表示内核允许分配所有的物理内存,而不管当前的内存状态如何。

2:表示内核允许分配超过所有物理内存和交换空间总和的内存

 

4.修改Redis配置文件

1. 修改bind参数:注释掉该行,允许所有主机访问redis,默认只允许本地访问

查看代码
################################## NETWORK #####################################

# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all available network interfaces on the host machine.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
# Each address can be prefixed by "-", which means that redis will not fail to
# start if the address is not available. Being not available only refers to
# addresses that does not correspond to any network interfece. Addresses that
# are already in use will always fail, and unsupported protocols will always BE
# silently skipped.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1     # listens on two specific IPv4 addresses
# bind 127.0.0.1 ::1              # listens on loopback IPv4 and IPv6
# bind * -::*                     # like the default, all available interfaces
#
# ~~~ 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 on the
# IPv4 and IPv6 (if available) loopback interface addresses (this means Redis
# will only be able to accept client connections from the same host that it is
# running on).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT OUT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#bind 127.0.0.1 -::1(表示只允许本机访问redis,如果想要其他电脑能够访问redis,则需要将其注释掉)

2. 修改protected-mode

查看代码
# 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 (如果设置为yes,则外部网络将无法访问reids)

# 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(可根据自己需求进行修改)

3. 修改requirepass参数:配置redis密码,使用时需要输入:auth itany进行认证,认证后才能操作
redis

 

 

查看代码
# IMPORTANT NOTE: starting with Redis 6 "requirepass" is just a compatibility
# layer on top of the new ACL system. The option effect will be just setting
# the password for the default user. Clients will still authenticate using
# AUTH <password> as usually, or more explicitly with AUTH default <password>
# if they follow the new protocol: both will work.
#
# The requirepass is not compatable with aclfile option and the ACL LOAD
# command, these will cause requirepass to be ignored.
#
requirepass 123456

 config get requirepass:获取设置的密码

4.Redis其他参数

参数介绍

daemonize yes: 是否以后台daemon方式运行。

pidfile /var/run/redis.pid:当Redis以守护进程方式运行时,Redis默认会把pid写入/var/run/redis.pid文件,可以通过pidfile指定。

port 6379: 指定Redis监听端口,默认端口为6379。

timeout 300: 当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能。

loglevel verbose:  指定日志记录级别,Redis总共支持四个级别:debug、verbose、notice、warning,默认为verbose。

Logfile : 日志记录方式,默认为标准输出,可指定一个文件,将日志输出到这里。

databases 16: 设置开启数据库的数量,默认数据库为0。

 

save:表示在一定时间内执行一定数量的写操作时,自动保存快照。可设置多个条件。

#save 900 1   #900 秒内如果至少有 1 个 key 的值变化,则保存

#save 300 10  #300 秒内如果至少有 10 个 key 的值变化,则保存

#save 60 10000  # 60 秒内如果至少有 10000 个 key 的值变化,则保存

注意:也可以注释掉所有的 save 行来停用保存功能。

 

rdbcompression yes指定存储至本地数据库时是否压缩数据,默认为yes,Redis采用LZF压缩,如果为了节省CPU时间,可以关闭该选项,但会导致数据库文件变的巨大

dbfilename dump.rdb数据快照文件名(只是文件名,不包括目录)

dir ./  数据快照的保存目录(这个是目录)

 

slaveof 192.168.1.100 6379  设置当本机为slave服务时,设置master服务的IP地址及端口,在Redis启动时,它会自动从master进行数据同步

 

appendonly no是否开启appendonlylog,开启的话每次写操作会记一条log,这会提高数据抗风险能力,但影响效率。Redis在默认情况下是异步的把数据写入磁盘,如果不开启,可能会在断电时导致一                                 段时间内的数据丢失。因为 redis本身同步数据文件是按上面save条件来同步的,所以有的数据会在一段时间内只存在于内存中。默认为no。

appendfilename appendonly.aof 指定更新日志文件名,默认为appendonly.aof

 

appendfsync  everysec 指定更新日志条件,共有3个可选值:

                     no:表示等操作系统进行数据缓存同步到磁盘(快)

                     always:表示每次更新操作后手动调用fsync()将数据写到磁盘(慢,安全)

                     everysec:表示每秒同步一次(折衷,默认值)

 

maxmemory 8G指定Redis最大内存限制,Redis在启动时会把数据加载到内存中,达到最大内存后,Redis会先尝试清除已到期或即将到期的Key,当此方法处理后,仍然到达最大内存设置,将无法再进行写入操作,但仍然可以进行读取操作。Redis新的vm机制,会把Key存放内存,Value会存放在swap区。

 

maxclients 128设置同一时间最大客户端连接数,默认无限制,Redis可以同时打开的客户端连接数为Redis进程可以打开的最大文件描述符数,如果设置 maxclients 0,表示不作限制。当客户端连接数到达限制时,Redis会关闭新的连接并向客户端返回max number of clients reached错误信息。

 

5.Redis监控

1.判断客户端和服务器连接是否正常

登录客户端:

[ redis-bin]# ./redis-cli 
127.0.0.1:6379> auth 123456(登录密码)
OK
127.0.0.1:6379> get name
"tom"
127.0.0.1:6379>

2.输入:ping命令

客户端和服务器连接正常,返回PONG

127.0.0.1:6379> ping
PONG
127.0.0.1:6379> 

客户端和服务器连接不正常(网络不正常或服务器未能正常运行),返回连接异常:

Could not connect to Redis at 127.0.0.1:6379: Connection refused

 

2.Redis监控查看命令

Redis 监控最直接的方法就是使用系统提供的 info 命令,只需要执行下面一条命令,就能获得 Redis 系统的状态报告,结果会返回 Server、Clients、Memory、Persistence、Stats、Replication、CPU、Keyspace 8个部分。

# Server
redis_version:6.2.6
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:2dffedde6c3a81a6
redis_mode:standalone
os:Linux 3.10.0-1160.31.1.el7.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:4.8.5 #gcc版本

process_id:14688 # 当前 Redis 服务器进程id
process_supervised:no
run_id:67cd96a92df992dc28e294271201ba5dec4a4f99
tcp_port:6379
server_time_usec:1646303511795520 #运行时间(秒)
uptime_in_seconds:72664 #运行时间(天)
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:2136343
executable:/svr/software/redis/redis-bin/./redis-server
config_file:/svr/software/redis/redis-bin/redis.conf
io_threads_active:0

# Clients
connected_clients:2 #连接的客户端数量
cluster_connections:0
maxclients:10000
client_recent_max_input_buffer:24
client_recent_max_output_buffer:0
blocked_clients:0
tracking_clients:0
clients_in_timeout_table:0

# Memory
used_memory:895088  #Redis分配的内存总量
used_memory_human:874.11K
used_memory_rss:2891776 #Redis分配的内存总量(包括内存碎片)
used_memory_rss_human:2.76M
used_memory_peak:931984
used_memory_peak_human:910.14K #Redis所用内存的高峰值
used_memory_peak_perc:96.04%
used_memory_overhead:851232

# Persistence
loading:0
rdb_changes_since_last_save:0  #上次保存数据库之后,执行命令的次数
rdb_bgsave_in_progress:0  #后台进行中的 save 操作的数量
rdb_last_save_time:1646234448  #最后一次成功保存的时间点,以 UNIX 时间戳格式显示


rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:0
rdb_current_bgsave_time_sec:-1
rdb_last_cow_size:200704

# Stats
total_connections_received:26 #运行以来连接过的客户端的总数量
total_commands_processed:25 # 运行以来执行过的命令的总数量
instantaneous_ops_per_sec:0

expired_keys:0  #运行以来过期的 key 的数量
expired_stale_perc:0.00 
expired_time_cap_reached_count:0
expire_cycle_cpu_milliseconds:1732
evicted_keys:0  #运行以来删除过的key的数量
keyspace_hits:7 #命中key 的次数
keyspace_misses:1 

# Replication
role:master  #当前实例的角色master还是slave
connected_slaves:0
master_failover_state:no-failover
master_replid:6f0d6cd8cccf8ae4308ffab87e548877c0ee899d
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

# CPU
used_cpu_sys:42.364211
used_cpu_user:56.872590
used_cpu_sys_children:0.001671
used_cpu_user_children:0.000000
used_cpu_sys_main_thread:42.360832
used_cpu_user_main_thread:56.870196

# Modules

# Errorstats
errorstat_ERR:count=7
errorstat_NOAUTH:count=21

# Cluster
cluster_enabled:0

# Keyspace
db0:keys=2,expires=0,avg_ttl=0  #各个数据库的 key 的数量,以及带有生存期的 key 的数量

 

posted @ 2022-03-03 09:19  BlogMemory  阅读(230)  评论(0编辑  收藏  举报