CentOS7下使用shell脚本一键安装redis

657 阅读1分钟

使用脚本一键安装redis并启动,该脚本是论坛一个大佬写的,找不到原链接了,实在抱歉!!! 注意事项: 1、修改版本号后要确认版本号是否正确,保证wget能下载到源码 2、安装路径尽量不要更改,测试更改成/root/redis导致安装失败 3、安装失败可以检查下权限问题,是否用管理员权限执行的脚本

1、本地编写脚本

#!/bin/bash

VERSION=redis-6.2.4
PASSWORD=123456
INSTALL_DIR=/apps/redis
 
color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "
    elif [ $2 = "failure" -o $2 = "1"  ] ;then
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo
}
 
 
install() {
yum  -y install gcc jemalloc-devel || { color "安装软件包失败,请检查网络配置" 1 ; exit; }
 
wget http://download.redis.io/releases/${VERSION}.tar.gz || { color "Redis 源码下载失败" 1 ; exit; }
 
tar xf ${VERSION}.tar.gz
cd ${VERSION}
make -j 2 PREFIX=${INSTALL_DIR} install && color "Redis 编译安装完成" 0 || { color "Redis 编译安装失败" 1 ;exit ; }
 
 
ln -s ${INSTALL_DIR}/bin/redis-*  /usr/bin/
mkdir -p ${INSTALL_DIR}/{etc,log,data,run}
cp redis.conf  ${INSTALL_DIR}/etc/
 
sed -i -e 's/bind 127.0.0.1/bind 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
 
 
if id redis &> /dev/null ;then
    color "Redis 用户已存在" 1
else
    useradd -r -s /sbin/nologin redis
    color "Redis 用户创建成功" 0
fi
 
chown -R redis.redis ${INSTALL_DIR}
 ·
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
 
cat > /usr/lib/systemd/system/redis.service <<EOF
[Unit]
Description=Redis persistent key-value database
After=network.target
 
[Service]
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
systemctl daemon-reload
systemctl enable --now  redis &> /dev/null && color "Redis 服务启动成功,Redis信息如下:"  0 || { color "Redis 启动失败" 1 ;exit; }
sleep 2
redis-cli -a $PASSWORD INFO Server 2> /dev/null
 
}

install

2、上传文件到服务器并运行

sudo sh install_redis.sh

image.png

3、检查运行状态并设置开机启动

# 开机自动启动
systemctl enable redis
# 启动redis服务
systemctl start redis
# 查看服务状态
systemctl status redis
# 停止服务
systemctl stop redis
# 取消开机自动启动(卸载服务)
systemctl disabled redis

4、使用Another Redis Desktop Manager连接测试

使用密码登录 image.png 连接成功 image.png