本篇其實是可以和上篇合并的,但由于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
保存配置文件之后,重啟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:///commands#string
redis的安裝信息,請參閱上篇:Redis系列-安裝部署維護篇
|