如何在centos下配置redis开机自启动
2014/11/10补充:其实在redis的下载包中就包含了官方自带的启动脚本,路径在
/redis-stable/utils/redis_init_script
。在utils目录下也有安装redis-server的脚本。
1. 修改redis.conf,打开后台运行选项:
# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize yes
2. 编写脚本,vim /etc/init.d/redis:
# 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:在vim里直接复制粘贴,:wq
保存之后可能会存在丢失开头几个字符的问题(# ch
没有了,应该是编码BOM问题),导致 服务不支持 chkconfig,怎么解决呢?在使用vim打开,添加上# ch
注意2:如何你的redis设置了密码,在stop
的时候可能会出现 NOAUTH Authentication required
的错误,因为 $REDIS_CLI -p $REDISPORT SHUTDOWN
这行是通过客户端来连接redis服务关闭的,所以需要修改成$REDIS_CLI -p $REDISPORT -a password SHUTDOWN
,password
替换你的密码。
3. 执行权限:
chmod +x /etc/init.d/redis
4. 开机自启动:
# 尝试启动或停止redis
service redis start
service redis stop
# 开启服务自启动
chkconfig redis on