Redis系列-遠程連接redis並給redis加鎖

本篇其實是可以和上篇合併的,但由於blog太長編輯麻煩,閱讀累人,打算新開一篇, 方便閱讀查找。

假設兩臺redis服務器,ip分別爲:192.168.1.101和192.168.1.103,如何在101上通過redis-cli訪問103上的redis呢?在遠程連接103之前,先講下redis-cli的幾個關鍵參數:

用法:redis-cli [OPTIONS] [cmd [arg [arg ...]]]

-h <主機ip>,默認是127.0.0.1

-p <端口>,默認是6379

-a <密碼>,如果redis加鎖,需要傳遞密碼

--help,顯示幫助信息

通過對rendis-cli用法介紹,在101上連接103應該很簡單:

[root@xsf001 ~]# redis-cli -h 192.168.1.103 -p 6379
redis 192.168.1.103:6379> 
在101上對103設置個個string值 user.1.name=zhangsan

redis 192.168.1.103:6379> set user.1.name zhangsan
OK
        看到ok,表明設置成功了。然後直接在103上登陸,看能不能獲取到這個值。

[root@xsf003 utils]# redis-cli 
redis 127.0.0.1:6379> get user.1.name
"zhangsan"
        木錯吧,確實是zhangsan,這說明101上連的是103上的redis服務器。當然能夠成功連接103是有基本條件的,101上可以喝103上的6379端口通信。

人人都可以連接redis服務器是很危險的,我們需要給103上的redis設置個密碼,怎麼設置呢,需要編輯redis的配置文件/etc/redis/6379.conf

[root@xsf003 utils]# vim /etc/redis/6379.conf 
      找到# requirepass foobared 去掉前面的註釋#,並把foobared 替換爲你自己的密碼:hi, coder 

requirepass "hi, coder"
保存配置文件之後,重啓redis服務

[root@xsf003 utils]# /etc/init.d/redis_6379 stop
Stopping ...
Waiting for Redis to shutdown ...
Redis stopped
[root@xsf003 utils]# /etc/init.d/redis_6379 start
Starting Redis server...
101上重新連接103並獲取user.1.name的值

[root@xsf001 ~]# redis-cli -h 192.168.1.103 -p 6379
redis 192.168.1.103:6379> get user.1.name
(error) ERR operation not permitted
redis 192.168.1.103:6379> 
        爲什麼是error呢,當然是因爲連接103時沒傳遞密碼了,退出重新連

redis 192.168.1.103:6379> quit
[root@xsf001 ~]# redis-cli -h 192.168.1.103 -p 6379 -a "hi, coder"
redis 192.168.1.103:6379> get user.1.name
"zhangsan"

         看到zhangsan,說明你已經連接成功了。關於get、set    用法,在下個blog中講,沒有耐心的觀衆可以直接看這裏:http://redis.io/commands#string

redis的安裝信息,請參閱上篇:Redis系列-安裝部署維護篇

微信掃碼,關注公衆號,獲取更多文章

 最新動態,請訪問:51RTB



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章