Linux-redis编译安装

下载源码

复制代码
[root@centos7-liyj ~]#wget http://download.redis.io/releases/redis-5.0.7.tar.gz
--2022-06-13 12:04:33--  http://download.redis.io/releases/redis-5.0.7.tar.gz
Resolving download.redis.io (download.redis.io)... 45.60.125.1
Connecting to download.redis.io (download.redis.io)|45.60.125.1|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1984203 (1.9M) [application/octet-stream]
Saving to: ‘redis-5.0.7.tar.gz’

100%[===============================================================================>] 1,984,203   2.16MB/s   in 0.9s   

2022-06-13 12:04:34 (2.16 MB/s) - ‘redis-5.0.7.tar.gz’ saved [1984203/1984203]
复制代码

安装依赖包

[root@centos7-liyj ~]#yum -y install gcc jemalloc-devel

编译安装

[root@centos7-liyj ~]#tar xf redis-5.0.7.tar.gz -C /usr/local/src/
[root@centos7-liyj ~]#cd /usr/local/src/
[root@centos7-liyj /usr/local/src]#cd redis-5.0.7/
[root@centos7-liyj /usr/local/src/redis-5.0.7]#make PREFIX=/usr/local/redis install

配置变量

[root@centos7-liyj ~]#echo 'PATH=/usr/local/redis/bin:$PATH' > /etc/profile.d/redis.sh
[root@centos7-liyj ~]#. /etc/profile.d/redis.sh                   
[root@centos7-liyj ~]#red
red                        redis-benchmark            redis-check-rdb            redis-sentinel
redhat_lsb_trigger.x86_64  redis-check-aof            redis-cli                  redis-server

目录结构

复制代码
[root@centos7-liyj ~]#tree /usr/local/redis/
/usr/local/redis/
└── bin
    ├── redis-benchmark
    ├── redis-check-aof
    ├── redis-check-rdb
    ├── redis-cli
    ├── redis-sentinel -> redis-server
    └── redis-server

1 directory, 6 files
复制代码

准备相关目录和配置文件

[root@centos7-liyj ~]#mkdir /usr/local/redis/{etc,log,data,run}  #创建配置文件,日志,数据等
[root@centos7-liyj ~]#cp /usr/local/src/redis-5.0.7/redis.conf /usr/local/redis/etc/

前台启动redis

复制代码
[root@centos7-liyj ~]#redis-server /usr/local/redis/etc/redis.conf 
5337:C 13 Jun 2022 12:24:18.432 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
5337:C 13 Jun 2022 12:24:18.432 # Redis version=5.0.7, bits=64, commit=00000000, modified=0, pid=5337, just started
5337:C 13 Jun 2022 12:24:18.432 # Configuration loaded
5337:M 13 Jun 2022 12:24:18.433 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 5.0.7 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 5337
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

5337:M 13 Jun 2022 12:24:18.433 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
5337:M 13 Jun 2022 12:24:18.433 # Server initialized
5337:M 13 Jun 2022 12:24:18.433 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
5337:M 13 Jun 2022 12:24:18.433 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
5337:M 13 Jun 2022 12:24:18.433 * Ready to accept connections
复制代码

解决启动时的三个警告提示

  • tcp-backlog
WARNING: The TCP backlog setting of 511 cannot be enforced because
/proc/sys/net/core/somaxconn is set to the lower value of 128.

backlog参数控制的是三次握手的时候server端收到client ack确认号之后的队列值,即全连接队列

[root@centos7-liyj ~]#vim /etc/sysctl.conf 
[root@centos7-liyj ~]#cat /etc/sysctl.conf 
 net.core.somaxconn = 1024
  • vm.overcommit_memory
WARNING overcommit_memory is set to 0! Background save may fail under low memory
condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf
and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to
take effect.

内核参数说明:

0、表示内核将检查是否有足够的可用内存供应用进程使用;如果有足够的可用内存,内存申请允许;否则,内存申请失败,并把错误返回给应用进程。
1、表示内核允许分配所有的物理内存,而不管当前的内存状态如何
2、表示内核允许分配超过所有物理内存和交换空间总和的内存

  [root@centos7-liyj ~]#sysctl vm.overcommit_memory=1
  vm.overcommit_memory = 1

[root@centos7-liyj ~]#cat /etc/sysctl.conf    #添加到配置文件中

net.core.somaxconn = 1024
vm.overcommit_memory = 1
  • transparent hugepage
WARNING you have Transparent Huge Pages (THP) support enabled in your kernel.This will create latency and memory usage issues with Redis. To fix this issue
run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a
reboot. Redis must be restarted after THP is disabled.


警告:您在内核中启用了透明大页面(THP,不同于一般内存页的4k为2M)支持。 这将在Redis中造成延迟和内存使用问题。 
要解决此问题,请以root 用户身份运行命令“echo never
>/sys/kernel/mm/transparent_hugepage/enabled”,并将其添加到您的/etc/rc.local中,以便在重启后保留设置。
禁用THP后,必须重新启动Redis。
复制代码
[root@centos7-liyj ~]#vim /etc/rc.d/rc.local 
[root@centos7-liyj ~]#cat /etc/rc.d/rc.local 
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local
echo never > /sys/kernel/mm/transparent_hugepage/enabled
[root@centos7-liyj ~]#chmod +x /etc/rc.d/rc.local 
[root@centos7-liyj ~]#. /etc/rc.d/rc.local
复制代码

再次前台运行

复制代码
[root@centos7-liyj ~]#redis-server /usr/local/redis/etc/redis.conf 
5376:C 13 Jun 2022 12:44:03.041 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
5376:C 13 Jun 2022 12:44:03.041 # Redis version=5.0.7, bits=64, commit=00000000, modified=0, pid=5376, just started
5376:C 13 Jun 2022 12:44:03.041 # Configuration loaded
5376:M 13 Jun 2022 12:44:03.041 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 5.0.7 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 5376
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

5376:M 13 Jun 2022 12:44:03.042 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
5376:M 13 Jun 2022 12:44:03.042 # Server initialized
5376:M 13 Jun 2022 12:44:03.042 * DB loaded from disk: 0.000 seconds
5376:M 13 Jun 2022 12:44:03.042 * Ready to accept connections
复制代码

创建redis用户和数据目录

[root@centos7-liyj ~]#useradd -r -s /sbin/nologin redis
[root@centos7-liyj ~]#chown -R redis.redis /usr/local/redis/  #设置目录权限

编辑 redis 服务启动文件

复制代码
[root@centos7-liyj ~]#vim /usr/lib/systemd/system/redis.service
[root@centos7-liyj ~]#cat /usr/lib/systemd/system/redis.service
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf --supervised systemd     #对应文件路径
ExecStop=/bin/kill -s QUIT $MAINPID
Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target
复制代码

 

redis 启动

复制代码
[root@centos7-liyj ~]#systemctl daemon-reload   #加载service文件内容
[root@centos7-liyj ~]#systemctl start redis
[root@centos7-liyj ~]#systemctl status redis
● redis.service - Redis persistent key-value database
   Loaded: loaded (/usr/lib/systemd/system/redis.service; disabled; vendor preset: disabled)
   Active: active (running) since Mon 2022-06-13 12:52:55 CST; 13s ago
 Main PID: 5512 (redis-server)
   CGroup: /system.slice/redis.service
           └─5512 /usr/local/redis/bin/redis-server 127.0.0.1:6379

Jun 13 12:52:55 centos7-liyj redis-server[5512]: `-._    `-._`-.__.-'_.-'    _.-'
Jun 13 12:52:55 centos7-liyj redis-server[5512]: |`-._`-._    `-.__.-'    _.-'_.-'|
Jun 13 12:52:55 centos7-liyj redis-server[5512]: |    `-._`-._        _.-'_.-'    |
Jun 13 12:52:55 centos7-liyj redis-server[5512]: `-._    `-._`-.__.-'_.-'    _.-'
Jun 13 12:52:55 centos7-liyj redis-server[5512]: `-._    `-.__.-'    _.-'
Jun 13 12:52:55 centos7-liyj redis-server[5512]: `-._        _.-'
Jun 13 12:52:55 centos7-liyj redis-server[5512]: `-.__.-'
Jun 13 12:52:55 centos7-liyj redis-server[5512]: 5512:M 13 Jun 2022 12:52:55.490 # WARNING: The TCP backlog setti... 128.
Jun 13 12:52:55 centos7-liyj redis-server[5512]: 5512:M 13 Jun 2022 12:52:55.490 # Server initialized
Jun 13 12:52:55 centos7-liyj redis-server[5512]: 5512:M 13 Jun 2022 12:52:55.493 * Ready to accept connections
Hint: Some lines were ellipsized, use -l to show in full.
复制代码

创建命令软连接

复制代码
[root@centos7-liyj ~]#ln -sv /usr/local/redis/bin/redis-* /usr/bin//usr/bin/redis-benchmark’ -> ‘/usr/local/redis/bin/redis-benchmark’
‘/usr/bin/redis-check-aof’ -> ‘/usr/local/redis/bin/redis-check-aof’
‘/usr/bin/redis-check-rdb’ -> ‘/usr/local/redis/bin/redis-check-rdb’
‘/usr/bin/redis-cli’ -> ‘/usr/local/redis/bin/redis-cli’
‘/usr/bin/redis-sentinel’ -> ‘/usr/local/redis/bin/redis-sentinel’
‘/usr/bin/redis-server’ -> ‘/usr/local/redis/bin/redis-server’
[root@centos7-liyj ~]#ll /usr/local/redis/bin/
total 32772
-rwxr-xr-x 1 redis redis 4366848 Jun 13 12:15 redis-benchmark    #redis性能测试工具
-rwxr-xr-x 1 redis redis 8125264 Jun 13 12:15 redis-check-aof    #AOF文件检查工具
-rwxr-xr-x 1 redis redis 8125264 Jun 13 12:15 redis-check-rdb    #RDB文件检查工具
-rwxr-xr-x 1 redis redis 4807920 Jun 13 12:15 redis-cli          #客户端工具
lrwxrwxrwx 1 redis redis      12 Jun 13 12:15 redis-sentinel -> redis-server  #哨兵,软连接到server
-rwxr-xr-x 1 redis redis 8125264 Jun 13 12:15 redis-server       #redis 服务启动命令
复制代码

 

连接到奥redis

主要分为客户端连接和程序的连接

客户端连接redis

本机无密码连接

redis-cli

跨主机无密码连接

redis-cli -h HOSTNAME/IP -p PORT

跨主机密码连接

redis-cli -h HOSTNAME/IP -p PORT -a PASSWORD

程序连接 Redis

redis 支持多种开发语言访问

 

脚本写入测试数据

shell 脚本写入数据到 Redis

复制代码
[root@centos8 ~]#cat redis_test.sh
#!/bin/bash
NUM=100
PASS=123456
for i in `seq $NUM`;do
   redis-cli -h 127.0.0.1 -a "$PASS"  --no-auth-warning  set key${i} value${i}
    echo "key${i} value${i} 写入完成"
done
echo "$NUM个key写入到Redis完成"
复制代码

python脚本写入数据到 Redis

复制代码
[root@centos8 ~]#yum -y install python3 python3-redis
#注意文件名不要为redis,会和redis模块名称冲突
[root@centos8 ~]#cat redis_test.py
#!/bin/env python3
import redis
#import time
pool = redis.ConnectionPool(host="127.0.0.1",port=6379,password="")
r = redis.Redis(connection_pool=pool)
for i in range(100):
 r.set("k%d" % i,"v%d" % i)
# time.sleep(1)
 data=r.get("k%d" % i)
 print(data)
[root@centos8
~]# python3 redis_test.py
复制代码

 

 

redis 的多实例

测试环境中经常使用多实例,需要指定不同实例的相应的端口,配置文件,日志文件等相关配置

以编译安装为例实现 redis 多实例

复制代码
[root@centos7-liyj ~]#ll /usr/local/redis/  #redis的文件列表
total 0
drwxr-xr-x 2 redis redis 134 Jun 13 12:15 bin
drwxr-xr-x 2 redis redis   6 Jun 13 12:21 data
drwxr-xr-x 2 redis redis  24 Jun 13 12:22 etc
drwxr-xr-x 2 redis redis   6 Jun 13 12:21 log
drwxr-xr-x 2 redis redis   6 Jun 13 12:21 run

[root@centos7 ~]#tree /usr/local/redis/
/usr/local/redis/
├── bin
│   ├── redis-benchmark
│   ├── redis-check-aof
│   ├── redis-check-rdb
│   ├── redis-cli
│   ├── redis-sentinel -> redis-server
│   └── redis-server
├── data
│   ├── dump_6379.rdb
│   ├── dump_6380.rdb
│   └── dump_6381.rdb
├── etc
│   ├── redis_6379.conf
│   ├── redis_6380.conf
│   └── redis_6381.conf
├── log
│   ├── redis_6379.log
│   ├── redis_6380.log
│   └── redis_6381.log
└── run
   ├── redis_6379.pid
   ├── redis_6380.pid
   └── redis_6381.pid

[root@centos7 ~]#grep '^[^#]' /usr/local/redis/etc/redis_6379.conf
bind 0.0.0.0
protected-mode yes
port 6379
tcp-backlog 511
timeout 0
tcp-keepalive 300
daemonize yes
supervised no
pidfile /usr/local/redis/run/redis_6379.pid
loglevel notice
logfile "/usr/local/redis/log/redis_6379.log"
databases 16
always-show-logo yes
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump_6379.rdb
dir /usr/local/redis/data/
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
replica-priority 100
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
appendonly no
appendfilename "appendonly_6379.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
stream-node-max-bytes 4096
stream-node-max-entries 100
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
dynamic-hz yes
aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes

[root@centos7 ~]#grep 6380 /usr/local/redis/etc/redis_6380.conf
# Accept connections on the specified port, default is 6380 (IANA #815344).
port 6380
pidfile /usr/local/redis/run/redis_6380.pid
logfile "/usr.local/redis/log/redis_6380.log"
dbfilename dump_6380.rdb
appendfilename "appendonly_6380.aof"
# cluster-config-file nodes-6380.conf
# cluster-announce-port 6380
# cluster-announce-bus-port 6380
[root@centos7 ~]#grep 6381 /usr/local/redis/etc/redis_6381.conf
# Accept connections on the specified port, default is 6381 (IANA #815344).
port 6381
pidfile /usr/local/redis/run/redis_6381.pid
logfile "/usr/local/redis/log/redis_6381.log"
dbfilename dump_6381.rdb
appendfilename "appendonly_6381.aof"
# cluster-config-file nodes-6381.conf
# cluster-announce-port 6381


[root@centos7 ~]#cat /lib/systemd/system/redis6379.service
[Unit]
Description=Redis persistent key-value database
After=network.target
[Service]
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis_6379.conf --
supervised systemd
#ExecStop=/usr/libexec/redis-shutdown
ExecStop=/bin/kill -s QUIT $MAINPID
Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755
[Install]
WantedBy=multi-user.target
[root@centos7 ~]#cat /lib/systemd/system/redis6380.service
[Unit]
Description=Redis persistent key-value database
After=network.target
[Service]
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis_6380.conf --
supervised systemd
#ExecStop=/usr/libexec/redis-shutdown
ExecStop=/bin/kill -s QUIT $MAINPID
Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755
[Install]
WantedBy=multi-user.target
[root@centos7 ~]#cat /lib/systemd/system/redis6381.service
[Unit]
Description=Redis persistent key-value database
After=network.target
[Service]
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis_6381.conf --
supervised systemd
#ExecStop=/usr/libexec/redis-shutdown
ExecStop=/bin/kill -s QUIT $MAINPID
Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755
[Install]
WantedBy=multi-user.target


[root@centos7 ~]#systemctl daemon-reload
[root@centos7 ~]#systemctl enable --now redis6379 redis6380 redis6381
[root@centos7 ~]#ss -ntl
多实例文件目录和配置信息
复制代码

 

redis 常用命令

INFO   显示当前节点redis运行状态信息

SELECT 切换数据库,相当于在MySQL的 USE DBNAME 指令
KEYS  查看当前库下的所有key,此命令慎用!
BGSAVE  手动在后台执行RDB持久化操作
DBSIZE    返回当前库下的所有key 数量
FLUSHDB  强制清空当前库中的所有key,此命令慎用!
FLUSHALL  强制清空当前redis服务器所有数据库中的所有key,即删除所有数据,此命令慎用!

SHUTDOWN

复制代码
可用版本: >= 1.0.0
时间复杂度: O(N),其中 N 为关机时需要保存的数据库键数量。
SHUTDOWN 命令执行以下操作:
停止所有客户端

如果有至少一个保存点在等待,执行 SAVE 命令
如果 AOF 选项被打开,更新 AOF 文件
关闭 redis 服务器(server)
如果持久化被打开的话, SHUTDOWN 命令会保证服务器正常关闭而不丢失任何数据。
另一方面,假如只是单纯地执行 SAVE 命令,然后再执行 QUIT 命令,则没有这一保证 —— 因为在执行
SAVE 之后、执行 QUIT 之前的这段时间中间,其他客户端可能正在和服务器进行通讯,这时如果执行 QUIT
就会造成数据丢失。
复制代码

 

posted @   goodbay说拜拜  阅读(183)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示