centos7脚本部署redis

#!/bin/bash

#centos7默认安装3.2.12,要安装较新版本,必须编译安装

 

. /etc/init.d/functions


VERSION=redis-6.2.7
PASSWORD=123456
INSTALL_DIR=/apps/redis

install() {

#安装依赖包
yum -y install gcc jemalloc-devel || { action "安装软件包失败,请检查网络配置" false; exit; }

#下载源码并解压
#官网下载: http://download.redis.io/releases/
#国内镜像 https://mirrors.huaweicloud.com/redis/
wget https://mirrors.huaweicloud.com/redis/${VERSION}.tar.gz || { action "Redis源码下载失败" false; exit; }
tar xzf ${VERSION}.tar.gz
cd ${VERSION}
#指定redis安装目录
make -j 4 PREFIX=${INSTALL_DIR} install && action "Redis编译安装完成" || { action "Redis编译安装失败" false; exit; }

ln -s ${INSTALL_DIR}/bin/redis-* /usr/bin/
mkdir -p ${INSTALL_DIR}/{etc,log,data,run}
cp redis.conf /apps/redis/etc/

#使其他机器的redis-cli也能登录本机redis-server,默认端口6379
sed -i -e '/^bind/s/127.0.0.1/0.0.0.0/' \
-e "/# requirepass/a requirepass ${PASSWORD}" \
-e "/^dir .*/c dir ${INSTALL_DIR}/data/" \
-e "/logfile .*/c logfile ${INSTALL_DIR}/log/redis_6379.log" \
-e "/^pidfile .*/c pidfile ${INSTALL_DIR}/run/redis_6379.pid" ${INSTALL_DIR}/etc/redis.conf

#创建redis用户
if id redis &> /dev/null ;then
action "redis 用户已存在" false
else
useradd -r -s /sbin/nologin redis
action "redis 用户创建成功"
fi

chown -R redis.redis ${INSTALL_DIR}

# 默认配置下,启动后的WARNING提示
# 5805:M 06 Jul 2022 19:48:40.851 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
# 5805:M 06 Jul 2022 19:48:40.851 # Server initialized
# 5805:M 06 Jul 2022 19:48:40.851 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
#消除上述WARNING提示
cat >> /etc/sysctl.conf <<EOF
net.core.somaxconn = 1024
vm.overcommit_memory = 1
EOF
sysctl -p

echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local
/etc/rc.d/rc.local

#前台启动redis
#redis-server /apps/redis/etc/redis.conf

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

[Service]
#WorkingDirectory=${INSTALL_DIR}
ExecStart=${INSTALL_DIR}/bin/redis-server ${INSTALL_DIR}/etc/redis.conf --supervised systemd
ExecStop=/bin/kill -s QUIT \$MAINPID
#Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target
EOF

#检查redis启动
systemctl daemon-reload
systemctl enable --now redis &>/dev/null && action "redis 服务启动成功" || { action "redis 服务启动失败" false; exit; }

redis-cli -a ${PASSWORD} info server 2> /dev/null

#end of install
}

install

posted @ 2022-07-06 23:49  joechenyao  阅读(39)  评论(2)    收藏  举报