本文紀錄在CentOS 7上安裝Redis並連接Spring Boot專案的過程。

安裝

可以使用yum或wget直接從官網下載安裝包,這裡選擇使用wget
官方下載連結,現在最新版本為7.0.11

1
wget https://download.redis.io/releases/redis-7.0.11.tar.gz

下載完後redis-7.0.11.tar.gz會放在 /usr/local 底下,需要先解壓縮

1
tar -zxvf redis-7.0.11.tar.gz -C /usr/local

就可以看到解壓縮後的資料夾 redis-7.0.11
接者要安裝C語言的編譯環境

1
yum -y install gcc automake autoconf libtool make

然後編譯安裝Redis
先cd 到 /usr/local/redis-7.0.11

1
cd /usr/local/redis-7.0.11

編譯

1
make && make install

這樣就完成Redis的安裝,可以使用以下指令執行Redis(在/usr/local/redis-7.0.11下)

1
./src/redis-server

配置環境變數

為了在全局都可以執行Redis的指令,而不是只能在redis-7.0.11下執行,要配置環境變數
使用vim開啟/etc/profile

1
vim /etc/profile

新增以下指令,注意後面的路徑要是安裝Redis的路徑

1
export PATH=$PATH:/usr/local/redis-7.0.11/bin

編輯完存儲後,刷新一下

1
source /etc/profile

這樣就可以在全局執行

1
2
redis-cli
redis-server

等指令囉!

讓Spring Boot專案可以連接上Redis

先編輯Redis的配置文件

1
vim /usr/local/redis-7.0.11/redis.conf

分別找到以下設定

1
2
3
4
5
protected-mode yes

bind 127.0.0.1

daemonize no

改成

1
2
3
4
5
protected-mode no             (關閉保護模式)

#bind 127.0.0.1 (註解掉這行)

daemonize yes (允許在後台執行Redis)

儲存後使用這個redis.conf啟動Redis

1
2
redis-cli shutdown                                     (如果Redis還是開啟的話先關掉)
redis-server /usr/local/redis-7.0.11/redis.conf (使用redis.conf啟動Redis)

然後要將CentOS防火牆的6379 Port開啟

1
2
sudo firewall-cmd --add-port=6379/tcp --permanent
sudo firewall-cmd --reload

最後在Spring Boot專案中的pom.xml,新增Redis的依賴

1
2
3
4
5
6
7
8
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>

在application.properties中

1
2
spring.redis.host=[ip位置]
spring.redis.port=6379

這樣就可以成功的讓Spring Boot專案與Redis連接了!

參考資料

Centos7安装redis
Linux CentOS 7 下 Redis 的配置
超详细:Springboot连接centos7下redis6的必要配置和失败分析

__END__