Linux自定义服务开机启动(如:Redis、MySQL、zookeeper、Tomcat 等)

一、整体步骤(基于你各项服务都装好过了,后三项基本一致)

创建编辑脚本文件》》》配置脚本文件权限》》》配置开机自启》》》测试

二、拆分

以 Redis 为例,文末会带上其它服务的脚本

创建脚本文件

vim /etc/init.d/redis

编辑脚本文件(注意替换成自己本地服务地址)

#!/bin/bash
#chkconfig: 22345 10 90
#description: Start and Stop redis

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

PIDFILE=/var/run/redis.pid
CONF="/usr/local/redis/etc/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
        ;;
    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
        ;;
    restart)
        "$0" stop
        sleep 3
        "$0" start
        ;;
    *)
        echo "Please use start or stop or restart as first argument"
        ;;
esac

修改文件权限

chmod +x /etc/init.d/redis

配置开机自启(add 与上面文件对应)

chkconfig --add /etc/init.d/redis
chkconfig redis on

测试(最直接的办法就是重启Linux然后看服务有没有启动 ps -ef|grep redis)

/etc/init.d/redis start

/etc/init.d/redis stop

其它服务脚本 (注意替换成你自己的服务路径)

zookeeper

#!/bin/bash
#chkconfig:2345 20 90
#description:zookeeper
#processname:zookeeper
export JAVA_HOME=/usr/local/java
case $1 in
        start) su root /usr/local/zookeeper/bin/zkServer.sh start;;
        stop) su root /usr/local/zookeeper/bin/zkServer.sh stop;;
        status) su root /usr/local/zookeeper/bin/zkServer.sh status;;
        restart) su /usr/local/zookeeper/bin/zkServer.sh restart;;
        *) echo "require start|stop|status|restart" ;;
esac

tomcat

#!/bin/bash
# description: Tomcat Start Stop Restart
# processname: tomcat
# chkconfig: 2345 20 80
#idea - tomcat config start 
#!/bin/bash
# description: Tomcat Start Stop Restart
# processname: tomcat
# chkconfig: 2345 20 80
JAVA_HOME=/usr/local/java
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH
CATALINA_HOME=/usr/local/tomcat
case $1 in
start)
sh $CATALINA_HOME/bin/startup.sh
;;
stop)
sh $CATALINA_HOME/bin/shutdown.sh
;;
restart)
sh $CATALINA_HOME/bin/shutdown.sh
sh $CATALINA_HOME/bin/startup.sh
;;
esac
exit 0
#chmod 755 tomcat
#chkconfig --add tomcat
#chkconfig --level 2345 tomcat on

你可能感兴趣的:(点滴汇聚,linux,redis,mysql)