Redis安装

Redis安装

一、下载

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

二、安装

方法一:

[root@server soft]# yum install gcc  tcl
[root@server soft]# wget https://download.redis.io/releases/redis-6.2.4.tar.gz
[root@server soft]# tar zxvf redis-6.2.4.tar.gz -C /opt/
[root@server soft]# cd /opt/redis-6.2.4/
[root@server redis-redis-6.2.4]# make
[root@server redis-redis-6.2.4]# cd src/
[root@server src]# make install
[root@server src]# make test
[root@server src]# ln -s /opt/redis-6.2.4/ /usr/local/redis
[root@server src]# make test

方法二:
[root@server soft]# tar xvf redis-6.0.10.tar.gz -C /usr/local/
[root@server soft]# cd /usr/local/
[root@server local]# ln -s redis-6.0.10 redis
[root@server src]# cd redis
[root@server redis]# make
[root@server redis]# cd redis/src
[root@server src]# make PREFIX=/usr/local/redis install
[root@server src]# make test

三、配置PATH环境变量

[root@server ~]# vi /etc/profile
export PATH=/usr/local/redis/bin:$PATH

[root@server ~]# source /etc/profile

四、启动和停止redis

  • 启动redis
[root@server ~]# redis-server
14768:C 11 Feb 2021 08:36:03.978 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
14768:C 11 Feb 2021 08:36:03.978 # Redis version=6.0.10, bits=64, commit=00000000, modified=0, pid=14768, just started
14768:C 11 Feb 2021 08:36:03.978 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
14768:M 11 Feb 2021 08:36:03.979 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 6.0.10 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 14768
  `-._    `-._  `-./  _.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           http://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'

14768:M 11 Feb 2021 08:36:03.980 # Server initialized
14768:M 11 Feb 2021 08:36:03.981 * Loading RDB produced by version 6.0.10
14768:M 11 Feb 2021 08:36:03.981 * RDB age 50325 seconds
14768:M 11 Feb 2021 08:36:03.981 * RDB memory usage when created 0.77 Mb
14768:M 11 Feb 2021 08:36:03.981 * DB loaded from disk: 0.001 seconds
14768:M 11 Feb 2021 08:36:03.981 * Ready to accept connections
  • 停止redis
[root@server ~]# redis-cli shutdown

五、自定义端口启动

[root@server ~]# redis-server --port 1314
14881:C 11 Feb 2021 08:45:41.001 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
14881:C 11 Feb 2021 08:45:41.001 # Redis version=6.0.10, bits=64, commit=00000000, modified=0, pid=14881, just started
14881:C 11 Feb 2021 08:45:41.001 # Configuration loaded
14881:M 11 Feb 2021 08:45:41.002 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 6.0.10 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 1314
 |    `-._   `._    /     _.-'    |     PID: 14881
  `-._    `-._  `-./  _.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           http://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'

14881:M 11 Feb 2021 08:45:41.002 # Server initialized
14881:M 11 Feb 2021 08:45:41.002 * Loading RDB produced by version 6.0.10
14881:M 11 Feb 2021 08:45:41.002 * RDB age 398 seconds
14881:M 11 Feb 2021 08:45:41.002 * RDB memory usage when created 0.82 Mb
14881:M 11 Feb 2021 08:45:41.002 * DB loaded from disk: 0.000 seconds
14881:M 11 Feb 2021 08:45:41.002 * Ready to accept connections

关闭redis:
[root@server ~]# redis-cli -p 1314 shutdown

六、配置启动脚本及参数文件

  • 目录结构
/etc/redis                            ---存放redis配置文件
/etc/init.d/redis_端口号              ---存放redis启动脚本
/var/redis/端口号                     ---存放redis持久化文件
/var/run/redis_端口号                 ---存放redis PID进程
  • 配置启动脚本
[root@server ~]# cp /usr/local/redis/utils/redis_init_script /etc/init.d/redis_1314

[root@server ~]# more /etc/init.d/redis_1314
#!/bin/sh
#
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.

### BEGIN INIT INFO
# Provides:     redis_6379
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Redis data structure server
# Description:          Redis data structure server. See https://redis.io
### END INIT INFO

REDISPORT=6379
EXEC=/usr/local/bin/redis-server
CLIEXEC=/usr/local/bin/redis-cli

PIDFILE=/var/run/redis_${REDISPORT}.pid
CONF="/etc/redis/${REDISPORT}.conf"

case "$1" in
    start)
        if [ -f $PIDFILE ]
        then
                echo "$PIDFILE exists, process is already running or crashed"
        else
                echo "Starting Redis server..."
                $EXEC $CONF
        fi
        ;;
    stop)
        if [ ! -f $PIDFILE ]
        then
                echo "$PIDFILE does not exist, process is not running"
        else
                PID=$(cat $PIDFILE)
                echo "Stopping ..."
                $CLIEXEC -p $REDISPORT shutdown
                while [ -x /proc/${PID} ]
                do
                    echo "Waiting for Redis to shutdown ..."
                    sleep 1
                done
                echo "Redis stopped"
        fi
        ;;
    *)
        echo "Please use start or stop as first argument"
        ;;
esac

修改启动脚本:
REDIS_HOME=/usr/local/redis
REDISPORT=1314
EXEC=$REDIS_HOME/bin/redis-server
CLIEXEC=$REDIS_HOME/bin/redis-cli

[root@server ~]# vim /etc/init.d/redis_1314
#!/bin/sh
#
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.

### BEGIN INIT INFO
# Provides:     redis_6379
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Redis data structure server
# Description:          Redis data structure server. See https://redis.io
### END INIT INFO

REDIS_HOME=/usr/local/redis
REDISPORT=1314
EXEC=$REDIS_HOME/bin/redis-server
CLIEXEC=$REDIS_HOME/bin/redis-cli

PIDFILE=/var/run/redis_${REDISPORT}.pid
CONF="/etc/redis/${REDISPORT}.conf"

case "$1" in
    start)
        if [ -f $PIDFILE ]
        then
                echo "$PIDFILE exists, process is already running or crashed"
        else
                echo "Starting Redis server..."
                $EXEC $CONF
        fi
        ;;
    stop)
        if [ ! -f $PIDFILE ]
        then
                echo "$PIDFILE does not exist, process is not running"
        else
                PID=$(cat $PIDFILE)
                echo "Stopping ..."
                $CLIEXEC -p $REDISPORT shutdown
                while [ -x /proc/${PID} ]
                do
                    echo "Waiting for Redis to shutdown ..."
                    sleep 1
                done
                echo "Redis stopped"
        fi
        ;;
    *)
        echo "Please use start or stop as first argument"
        ;;
esac
  • 配置redis配置文件
[root@server ~]# mkdir /etc/redis
[root@server ~]# mkdir -p /var/redis/1314
[root@server ~]# cp /usr/local/redis/redis.conf /etc/redis/1314.conf

修改配置文件:
需要修改的内容:
daemonize     yes                        ---使用redis以守护进程模式运行
port          1314
pidfile       /var/run/redis_1314.pid
dir           /var/redis/1314            ---持久化文件存放位置

[root@server ~]# grep -v '#'  /etc/redis/1314.conf |grep 6379
port 6379
pidfile /var/run/redis_6379.pid

[root@server ~]# grep -v '#' /etc/redis/1314.conf |grep dir
dir ./

[root@server ~]# sed -i 's/daemonize no/daemonize yes/' /etc/redis/1314.conf
[root@server ~]# sed -i 's/6379/1314/g' /etc/redis/1314.conf
  • 配置持久化文件
[root@server ~]# grep -v '#' /etc/redis/1314.conf |grep dir
dir ./

修改成 dir /var/redis/1314,即文件保存在/var/redis/1314

七、配置redis启动

1.sys-v启动redis
[root@server ~]# /etc/init.d/redis_1314 start
Starting Redis server...
2.systemd启动redis
[root@server ~]# vi /etc/systemd/system/redis.service

[Unit]
Description=Redis
After=network.target

[Service]
Type=forking
PIDFile=/var/run/redis_1314.pid
ExecStart=/usr/local/redis/bin/redis-server /etc/redis/1314.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/usr/local/redis/bin/redis-cli -p 1314 shutdown
PrivateTmp=true

[Install]
WantedBy=multi-user.target

加载服务:
[root@server ~]# systemctl daemon-reload
[root@server ~]# systemctl enable redis
[root@server ~]# systemctl start redis
[root@server ~]# systemctl status redis

八、redis自动启动

redis随系统自动启动:
update-rc.d redis_1314 defaults

九、安装过程中报错处理

(1). 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.

[root@vip redis-4.0.10]# vim /etc/sysctl.conf
vm.overcommit_memory = 1
[root@vip redis-4.0.10]# sysctl -p

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

[root@vip src]# more /proc/sys/net/core/somaxconn
128
[root@vip src]# echo 511 > /proc/sys/net/core/somaxconn
[root@vip src]# more /proc/sys/net/core/somaxconn
511

如果想要永久解决,打开/etc/sysctl.conf
在这里面添net.core.somaxconn= 1024 然后执行sysctl -p 就可以永久消除这个warning
或者将其写入/etc/rc.local文件中:
[root@vip redis-4.0.10]# vim /etc/rc.local
echo 511 > /proc/sys/net/core/somaxconn

(3). 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.

echo never > /sys/kernel/mm/transparent_hugepage/enabled
将其写入/etc/rc.local文件中:
[root@vip redis-4.0.10]# vim /etc/rc.local
echo never > /sys/kernel/mm/transparent_hugepage/enabled

温馨提示:
entos7 的/etc/rc.local不会开机执行,检查/etc/rc.local的权限
[root@server ~]# ll /etc/rc.local
lrwxrwxrwx. 1 root root 13 Mar  4 19:32 /etc/rc.local -> rc.d/rc.local
[root@server ~]# ll /etc/rc.d/rc.local
-rw-r--r--. 1 root root 572 Jul  3 00:08 /etc/rc.d/rc.local
[root@server ~]# chmod +x /etc/rc.d/rc.local
授权x权限后,重启生效

(4). Increased maximum number of open files to 10032 (it was originally set to 1024).

# ulimit -HSn 102400  //这只是在当前终端有效,退出之后,open files又变为默认值。当然也可以写到/etc/profile中,因为每次登录终端时,都会自动执行/etc/profile
或
# vim /etc/security/limits.conf  //加入以下配置,重启即可生效
* soft nofile 65535
* hard nofile 65535

[root@server ~]# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 14949
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 14949
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
[root@server ~]# ulimit -n 10032             只是在当前终端生效,退出后会失效

[root@server ~]# vim /etc/security/limits.conf          重启生效

* soft nofile 10032
* hard nofile 10032

(5).[exception]: Executing test client: NOREPLICAS Not enough good slaves to write..
NOREPLICAS Not enough good slaves to write.
    while executing
"[srv $level "client"] {*}$args"
    (procedure "r" line 7)
    invoked from within
"r set foo 12345"
    ("uplevel" body line 4)
    invoked from within
"uplevel 1 $code"
    (procedure "test" line 29)
    invoked from within
"test {If min-slaves-to-write is honored, write is accepted} {
            r config set min-slaves-to-write 1
            r config set min-slaves-max-l..."
    ("uplevel" body line 8)
    invoked from within
"uplevel 1 $code "
    (procedure "start_server" line 3)
    invoked from within
"start_server {} {
        test {First server should have role slave after SLAVEOF} {
            r -1 slaveof [srv 0 host] [srv 0 port]
            af..."
    ("uplevel" body line 2)
    invoked from within
"uplevel 1 $code "
    (procedure "start_server" line 3)
    invoked from within
"start_server {tags {"repl"}} {
    start_server {} {
        test {First server should have role slave after SLAVEOF} {
            r -1 slaveof [srv ..."
    (file "tests/integration/replication-2.tcl" line 1)
    invoked from within
"source $path"
    (procedure "execute_tests" line 4)
    invoked from within
"execute_tests $data"
    (procedure "test_client_main" line 10)
    invoked from within
"test_client_main $::test_server_port "
Killing still running Redis server 8636
Killing still running Redis server 8647
Killing still running Redis server 8637
Killing still running Redis server 8640
Killing still running Redis server 8635
Killing still running Redis server 8645
Killing still running Redis server 8639
Killing still running Redis server 8638
Killing still running Redis server 8646
Killing still running Redis server 8649
Killing still running Redis server 8910
Killing still running Redis server 8979
Killing still running Redis server 8999
Killing still running Redis server 9028
Killing still running Redis server 9044
I/O error reading reply

解决办法:
修改 tests/integration/replication-2.tcl,将after 1000改为after 10000以延长等待时间 重新执行make test
[root@server src]# cd /usr/local/redis
[root@server redis]# vi tests/integration/replication-2.tcl

start_server {tags {"repl"}} {
    start_server {} {
        test {First server should have role slave after SLAVEOF} {
            r -1 slaveof [srv 0 host] [srv 0 port]
            after 10000
            s -1 role

十、redis常用命令

1.redis-cli

-x: 从标准输入读取一个参数
-r: 设置命令重复执行次数
-i: 设置命令执行的时间间隔
--scan --pattern: 扫描redis中的key,代替keys *

--bigkeys: 找出较大的keys

[root@server ~]# echo -en "*" | redis-cli -p 1314 -x keys
[root@server ~]# redis-cli -r 5 -i 2 info
[root@server ~]# redis-cli -p 1314 --scan
name
age
[root@server ~]# redis-cli -p 1314 --scan --pattern n*
name
[root@server ~]# redis-cli -p 1314 --stat
------- data ------ --------------------- load -------------------- - child -
keys       mem      clients blocked requests            connections
2          796.91K  1       0       10 (+0)             11

[root@server ~]# redis-cli -p 1314 --bigkeys

# Scanning the entire keyspace to find biggest keys as well as
# average sizes per key type.  You can use -i 0.1 to sleep 0.1 sec
# per 100 SCAN commands (not usually needed).

[00.00%] Biggest string found so far 'name' with 8 bytes

-------- summary -------

Sampled 2 keys in the keyspace!
Total key length in bytes is 7 (avg len 3.50)

Biggest string found 'name' has 8 bytes

2 strings with 10 bytes (100.00% of keys, avg size 5.00)
0 lists with 0 items (00.00% of keys, avg size 0.00)
0 sets with 0 members (00.00% of keys, avg size 0.00)
0 hashs with 0 fields (00.00% of keys, avg size 0.00)
0 zsets with 0 members (00.00% of keys, avg size 0.00)
2.keys

-del key

-dump key

  • 按rdb的存储格式把指定的key的值序列化并返回给客户端,此序列化值不包含ttl信息
  • 序列化的值中包含校验码
  • key不存在则返回nil

-restore key ttl serialized-value [replace]

  • 把通过dump命令序列化的值再存进去
  • 如果没有带replace,且key已经存在,会出现错误

-exists key

-expire key seconds

  • 设置key的超时时间,单位是秒,当达到超时时间后,key会被删除
  • 可以通过persist把超时设置取消

-persist key

  • 移除key的超时设置
  • 返回1表示移除成功,返回0表示key不存在或key上没有超时设置

-ttl key

  • 返回key对应的超时时间,还剩余多少时间
  • 如果key不存在,返回-2
  • 如果key上没有设置超时时间,返回-1
127.0.0.1:1314> ttl name
(integer) -1
127.0.0.1:1314> expire name 20
(integer) 1
127.0.0.1:1314> ttl name
(integer) 16
127.0.0.1:1314> ttl name
(integer) 14
127.0.0.1:1314> ttl name
(integer) -2
127.0.0.1:1314> get name
(nil)

-pttl key

-scan

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇