在 CentOS 上安裝 Redis 有第二個方法,也是官網上所寫的方法,我也比較推崇這種方式,整個過程雖然修修改改,不過我也藉著這樣繁瑣的步驟了解到 Linux 對於 Daemon Service 的一些基本概念,而且敲很多指令很潮 XD。
安裝相關工具
- net-tools
- wget
- gcc
- tcl
#Install required tools
yum -y install net-tools wget gcc tcl
下載及解壓縮 Redis
# Download Redis
cd ~
wget http://download.redis.io/releases/redis-3.0.7.tar.gz
# Extract Redis
tar xzf redis-3.0.7.tar.gz
編譯 Redis
# Compile Redis
cd redis-3.0.7
make
測試及安裝 Redis
# Test and install Redis
make test
make install
建立相關目錄
# Create Redis directory
mkdir /etc/redis
mkdir /var/redis
複製設定檔
# Copy configuration file
cp ~/redis-3.0.7/redis.conf /etc/redis/redis_6379.conf
建立工作目錄
# Create working directory
mkdir /var/redis/6379
修改 Redis 參數值
# Set Redis settings
vi /etc/redis/redis_6379.conf
- 將 daemonize 的值修改為
yes
- 將 pidfile 的值修改為
/var/run/redis_6379.pid
- 將 logfile 的值修改為
/var/log/redis_6379.log
- 將 dir 的值修改為
/var/redis/6379
開啟防火牆 6379 埠號
# Add allow port 6379
firewall-cmd --permanent --add-port=6379/tcp
firewall-cmd --reload
設定 Redis 在開機時就啟動
要讓 Redis 在開機就啟動有兩種方式,第一種稍微麻煩了一點,請看下面。
複製初始啟動指令
# Copy init script
cp ~/redis-3.0.7/utils/redis_init_script /etc/init.d/redis_6379
修改初始啟動指令
# Modify init script
vi /etc/init.d/redis_6379
- 第2行修改為
# chkconfig: 2345 80 90
- 第11行修改為
CONF="/etc/redis/redis_${REDISPORT}.conf"
- 第20行增加
&
在最後面
#!/bin/sh
# chkconfig: 2345 80 90
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
REDISPORT=6379
EXEC=/usr/local/bin/redis-server
CLIEXEC=/usr/local/bin/redis-cli
PIDFILE=/var/run/redis_${REDISPORT}.pid
CONF="/etc/redis/redis_${REDISPORT}.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
;;
*)
echo "Please use start or stop as first argument"
;;
esac
註冊並啟動 Redis 服務
# Register Redis service
chkconfig --add redis_6379
# Start Redis service
service start redis_6379
上述這種用 chkconfig
來註冊初始指令碼,用 service
來啟動服務是 CentOS 7 以前的做法,在 CentOS 7 一樣通用,下面就來介紹第二種方法,這種方法只有 CentOS 7 才有。
建立 Redis 服務設定檔
# Create Redis service file
vi /lib/systemd/system/redis_6379.service
將下面的內容貼到檔案裡面,儲存並且離開。
[Unit]
Description=Redis on port 6379
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/bin/redis-server /etc/redis/redis_6379.conf
ExecStop=/usr/local/bin/redis-cli -p 6379 shutdown
[Install]
WantedBy=multi-user.target
註冊並啟動 Redis 服務
# Enable Redis service
systemctl daemon-reload
systemctl enable redis_6379.service
# Start Redis service
systemctl start redis_6379.service
用 CentOS 7 的 systemctl
工具只要兩三個步驟就搞定了。
Ping Redis
服務註冊完畢並啟動之後,就可以來試試看 Redis 有沒有正常運作。
# Ping Redis
redis-cli ping
有收到 PONG 就表示服務正活著