#!/usr/bin/bash

#Tate:2022.4.22
#Author:Yingjian
#Function：一键编译安装redis

num=`ps -ef |grep -v grep |grep redis|wc -l`

if [ ! $num -eq 0 ];then
echo "redis 服务已存在"
exit 2    
fi

#判断是否有redis安装目录

if [ -d "/usr/local/redis" ];then
echo "nginx 已安装" 
exit 2
fi

#判断是否有redis源码包

if [ ! -f "/usr/local/src/redis-5.0.5.tar.gz" ];then
curl -o /usr/local/src/redis-5.0.5.tar.gz -s http://8.210.62.122/redis/redis-5.0.5.tar.gz
else
echo "redis包已安装"
fi

yum -y install gcc  gcc-c++  make pcre-devel zlib-devel openssl-devel &>/dev/null

tar xf /usr/local/src/redis-5.0.5.tar.gz -C /usr/local

id redis
if [ ! $? -eq 0 ];then
useradd -M redis -s /sbin/nologin
else
echo "redis用户已创建"
fi

cd /usr/local/redis-5.0.5
make PREFIX=/usr/local/redis install
if [ ! $? -eq 0 ];then
echo "make 失败 请清理环境 重新安装"
fi

mkdir /usr/local/redis/{etc,data,log,run}
cp -ar /usr/local/redis-5.0.5/redis.conf /usr/local/redis/etc

cat > /etc/profile.d/redis.sh <<EOF
export REDIS_HOME=/usr/local/redis
export PATH=\$REDIS_HOME/bin:\$PATH
EOF

sed -i 's/^bind.*/bind 0.0.0.0/' /usr/local/redis/etc/redis.conf
sed -i 's/^daemonize.*/daemonize yes/' /usr/local/redis/etc/redis.conf
sed -i 's@^pidfile.*@pidfile /usr/local/redis/run/redis_6379.pid@' /usr/local/redis/etc/redis.conf
sed -i 's@^logfile.*@logfile /usr/local/redis/log/redis.log@' /usr/local/redis/etc/redis.conf
sed -i 's@^dir.*@dir /usr/local/redis/data@' /usr/local/redis/etc/redis.conf

echo "never" > /sys/kernel/mm/transparent_hugepage/enabled

echo -e "net.core.somaxconn=32768\nnet.ipv4.tcp_max_syn_backlog=32768\nvm.overcommit_memory=1" >> /etc/sysctl.conf

sysctl -p

chown -R redis.redis /usr/local/redis

cat > /usr/lib/systemd/system/redis.service <<EOF
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf
Type=forking
User=redis
Group=redis
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=/bin/kill -s QUIT \$MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable redis
systemctl restart redis

echo "--------------redis 安装完成-----------"
