在 Linux 下配置 Redis 开机启动

在 Linux 下配置 Redis 开机启动,主要步骤如下:

  1. 设置 Redis redis.conf 文件,使之能够以后台模式运行
  2. 编写 shell 启动 Redis 脚本
  3. 配置 Linux 开机启动配置

实际操作:

  • 打开 redis.conf 文件,修改:#daemonize yesdaemonize yes
  • 编写 shell 脚本,输入vim /etc/init.d/redis
    下面有两段代码任选一段都可以使用,都是 Centos 可用的启动 Redis 脚本,其中的文件位置需要根据实际情况修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# chkconfig: 2345 10 90
# description: Start and Stop redis
PATH=/usr/local/bin:/sbin:/usr/bin:/bin
REDISPORT=6379 #实际环境而定
EXEC=/usr/local/redis/src/redis-server #实际环境而定
REDIS_CLI=/usr/local/redis/src/redis-cli #实际环境而定
PIDFILE=/var/run/redis.pid
CONF="/usr/local/redis/redis.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
if [ "$?"="0" ]
then
echo "Redis is running..."
fi
;;
stop)
if [ ! -f $PIDFILE ]
then
echo "$PIDFILE exists, process is not running."
else
PID=$(cat $PIDFILE)
echo "Stopping..."
$REDIS_CLI -p $REDISPORT SHUTDOWN
while [ -x $PIDFILE ]
do
echo "Waiting for Redis to shutdown..."
sleep 1
done
echo "Redis stopped"
fi
;;
restart|force-reload)
${0} stop
${0} start
;;
*)
echo "Usage: /etc/init.d/redis {start|stop|restart|force-reload}" >&2
exit 1
esac

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/bin/sh
#chkconfig: 345 86 14
#description: Startup and shutdown script for Redis
PROGDIR=/usr/local/bin
PROGNAME=redis-server
DAEMON=$PROGDIR/$PROGNAME
CONFIG=/etc/redis.conf
PIDFILE=/var/run/redis.pid
DESC="redis daemon"
SCRIPTNAME=/etc/init.d/redis
start()
{
if test -x $DAEMON
then
echo -e "Starting $DESC: $PROGNAME"
if $DAEMON $CONFIG
then
echo -e "OK"
else
echo -e "failed"
fi
else
echo -e "Couldn't find Redis Server ($DAEMON)"
fi
}
stop()
{
if test -e $PIDFILE
then
echo -e "Stopping $DESC: $PROGNAME"
if kill `cat $PIDFILE`
then
echo -e "OK"
else
echo -e "failed"
fi
else
echo -e "No Redis Server ($DAEMON) running"
fi
}
restart()
{
echo -e "Restarting $DESC: $PROGNAME"
stop
start
}
list()
{
ps aux | grep $PROGNAME
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
list)
list
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|restart|list}" >&2
exit 1
;;
esac
exit 0

  • 为 shell 启动 Redis 脚本添加执行权限:chmod +x /etc/init.d/redis
  • 测试脚本是否可用,可执行 service redis start 进行启动,启动后可连接 Redis 进行测试
  • 如果脚本可用,即可将其配置为开机启动项,执行chkconfig redis on即可,设置后可使用chkconfig --list查看是否有 redis 选项,到此,完成配置流程结束
  • 这时候,可能在开机时仍然无法自动启动 Redis ,这是因为开机执行启动脚本 /etc/init.d/redis ,是没有输入参数的,所以都会走到脚本中的 *) 这里,所以此时需要修改上面的脚本,如第二个脚本,修改

1
2
3
4
*)
echo "Usage: $SCRIPTNAME {start|stop|restart|list}" >&2
exit 1
;;

 *)
 start
 ;;

参考

Centos开机自启动redis
ddkangfu/redis开机启动脚本
init.d里chkconfig(linux启动脚本讲解+示例)