以前公司在開發階段串連的Redis一直是正式環境中的,最近老大讓我在搭建一個區域網路內的redis用於開發階段時串連使用,搭建過程中也遇到了一些問題,還好已經解決了,在這裡記錄一下。
首先是搭建redis,這個比較簡單。
1、檢查安裝依賴程式
yum install gcc-c++yum install -y tclyum install wget
2、擷取安裝檔案
wget http://download.redis.io/releases/這裡面有很多版本,自己選擇需要的下載
3、解壓檔案
自己建立一個目錄將redis解壓到裡面
tar -zxvf redis-3.2.01.tar.gzmv redis-3.2.01 /usr/local/redis
4、進入目錄
cd /usr/local/redis
5、編譯安裝
makemake install
6、設定設定檔路徑
mkdir -p /etc/rediscp redis.conf/etc/redis
7、修改設定檔
redis.conf是redis的設定檔,redis.conf在redis源碼目錄。
注意修改port作為redis進程的連接埠,port預設6379。如果需要搭建redis叢集,千萬別忘了修改連接埠號碼。
redis有兩種啟動方式,直接運行bin/redis-server將以前端模式啟動,前端模式啟動的缺點是ssh命令視窗關閉則redis-server程式結束,不推薦使用此方法。如下圖:
後端模式啟動
修改redis.conf設定檔, daemonize yes 以後端模式啟動。推薦。
開啟redis.conf,使用命令 :/ daemonize 快速尋找到daemonize然後修改。
vi /etc/redis/redis.conf僅修改: daemonize yes (no-->yes)
8、啟動
/usr/local/bin/redis-server /etc/redis/redis.conf
9、查看啟動
ps -ef | grep redis
10、使用用戶端
redis-cli>set name davidOK>get name"david"
11.關閉用戶端
redis-cli shutdown
12、開機啟動配置
echo "/usr/local/bin/redis-server /etc/redis/redis.conf &" >> /etc/rc.local
開機啟動要配置在 rc.local 中,而 /etc/profile 檔案,要有使用者登入了,才會被執行。
13、設定密碼
因為這是給區域網路內的很多人使用,所以設定一個訪問密碼很有必要。
修改redis.conf檔案配置
使用命令 :/ requirepass 快速尋找到 # requirepass foobared 然後去掉注釋,這個foobared改為自己的密碼。然後wq儲存。
14、重啟redis
sudo service redis restart 這個時候嘗試登入redis,發現可以登上,但是執行具體命令是提示操作不允許 redis-cli -h 127.0.0.1 -p 6379 redis 127.0.0.1:6379> redis 127.0.0.1:6379> keys * (error) ERR operation not permitted
嘗試用密碼登入並執行具體的命令看到可以成功執行 redis-cli -h 127.0.0.1 -p 6379 -a password redis 127.0.0.1:6379> keys * 1) "myset" 2) "mysortset" redis 127.0.0.1:6379> select 1 OK
如果是自己在本機上使用現在已經可以了,因為我這是區域網路內提供給大家使用的所以還需要最後的配置。
當時修改開發的設定檔後,啟動項目報錯。
org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.Java:162) ~[spring-data-redis-1.5.0.RELEASE.jar:1.5.0.RELEASE]
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:251) ~[spring-data-redis-1.5.0.RELEASE.jar:1.5.0.RELEASE]
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:58) ~[spring-data-redis-1.5.0.RELEASE.jar:1.5.0.RELEASE]
at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:128) ~[spring-data-redis-1.5.0.RELEASE.jar:1.5.0.RELEASE]
開啟cmd 然後使用 telnet ip 連接埠 來ping 配置的redis(要保證redis已啟動),發現無法ping通。
這是因為在redis.conf中有個配置 bind 127.0.0.1 這個是預設只有本機訪問,把這個注釋掉就好了,注釋以後查看redis進程就變為下面這樣:
[root@localhost redis]# ps -ef | grep redis
root 5655 1 0 11:40 ? 00:00:23 ./redis-server *:6379
root 21184 18040 0 17:33 pts/1 00:00:00 grep --color=auto redis
這個*號就表示允許其它使用者訪問了。然後在用開啟原生 cmd使用 telnet ip 連接埠 就能ping通了。