#!/bin/bash
# 定义函数Usage,输出脚本使用方法
usage(){
echo "Usage: redisServer -c command [-e]"
echo ""
echo "Optional Command:"
echo " start:start redis service "
echo " example: -c start [-e];[-e] is cluster-enabled"
echo " stop:stop redis service "
echo " example: -c stop "
exit -1
}
# 安装redis
install(){
# 指定安装目录
mkdir -p /usr/local/redis
cd /usr/local/redis
# 安装expect和make
yum -y install expect
yum -y install make
# 从30机器上拉取安装包
if [[ ! -f "/redis-5.0.3.tar.gz" ]]
then
expect<<-END
set timeout 600
spawn scp root@192.100.3.30:/openPlatform/redis-5.0.3.tar.gz /
expect {
"(yes/no)?" { send "yes\r"; exp_continue }
"*assword:" { send "root123\r" }
}
expect
END
fi
# 解压编译
tar -xf /redis-5.0.3.tar.gz
cd redis-5.0.3/src
make
make MALLOC=libc
# 创建日志和数据保存目录
mkdir /usr/local/redis/data
cp /usr/local/redis/redis-5.0.3/redis.conf /usr/local/redis/redis-5.0.3/src/redis.conf
mkdir /usr/local/redis/log
# 修改redis配置文件
sed -i 's/logfile ""/logfile \/usr\/local\/redis\/log\/redis.log/g' redis.conf
sed -i 's/dir .\//dir \/usr\/local\/redis\/data/g' redis.conf
sed -i 's/daemonize no/daemonize yes/g' redis.conf
sed -i 's/bind 127.0.0.1/bind 0.0.0.0/g' redis.conf
sed -i 's/# cluster-node-timeout 15000/cluster-node-timeout 15000/g' redis.conf
sed -i 's/# cluster-replica-validity-factor 10/cluster-replica-validity-factor 10/g' redis.conf
sed -i 's/# cluster-migration-barrier 1/cluster-migration-barrier 1/g' redis.conf
# 开启防火墙,并开放6379和16379端口
systemctl start firewalld
firewall-cmd --zone=public --add-port=6379/tcp --permanent
firewall-cmd --zone=public --add-port=16379/tcp --permanent
firewall-cmd --reload
# 创建软连接
ln -f /usr/local/redis/redis-5.0.3/src/redis-cli /bin/redis-cli
}
# 启动redis服务,作为集群使用
start(){
filePath="/usr/local/redis/redis-5.0.3/src/redis.conf"
name="/usr/local/redis/redis-5.0.3/src/redis-server"
pid=`ps -ef | grep "$name"| grep -v grep| awk '{print $2}'`
if [[ $pid ]]
then
kill -9 ${pid}
fi
if [[ -f "$filePath" ]]
then
rm -rf /usr/local/redis/data/*
else
install
fi
if [[ $clusterEnabled -eq 1 ]]
then
sed -i 's/# cluster-enabled yes/cluster-enabled yes/g' $filePath
else
sed -i 's/cluster-enabled yes/# cluster-enabled yes/g' $filePath
fi
# 启动redis服务
$name $filePath
}
# 停止redis服务,作为新的节点
stop(){
name="redis-server"
pid=`ps -ef | grep "$name"| grep -v grep| awk '{print $2}'`
if [ $pid ]
then
kill -9 ${pid}
fi
if [[ -f "/usr/local/redis/redis-5.0.3/src/redis.conf" ]]
then
rm -rf /usr/local/redis/data/*
fi
}
# 获取参数列表,选项后面的冒号表示该选项需要参数
while getopts "c:e" arg
do
case $arg in
c)
#参数存在$OPTARG中
command=$OPTARG
;;
e)
#参数存在$OPTARG中
clusterEnabled=1
;;
?)
# 当有不认识的选项的时候arg为?
echo "unkonw argument"
usage
;;
esac
done
# 选择执行的指令
case $command in
"start")
start
;;
"stop")
if [[ $clusterEnabled -ne 1 ]]
then
stop
else
echo "stop:extra operand:'-e'"
usage
fi
;;
"")
usage
;;
*)
echo "Error:No such command"
usage
;;
esac