深刻淺出Redis05-Redis集羣環境的配置

1、安裝redis

1,下載redis最新版html

從如下redis地址下載最新版本的redis,使用使用redis-3.2.9.tar版本。java

http://download.redis.io/releases/

  這次,介紹安裝redis的環境, 如下是安裝環境的詳細信息。node

Linux版本: CentOS 6.5
IP 地址 : 192.168.253.140

  查看Linux版本,IP地址的命令:python

cat /etc/issue
ifconfig

  爲了安裝Redis環境,須要進行必要的測試,首先須要關閉Linux的防火牆。c++

# 關閉命令:  
service iptables stop
# 永久關閉防火牆
chkconfig iptables off

  兩個命令同時運行,運行完成後查看防火牆關閉狀態redis

service iptables status

 2,須要gcc環境,若是沒有執行命令安裝gcc算法

yum install gcc-c++

3,下載redis3.0的源碼包並上傳至服務器centos

4,解壓源碼包緩存

tar -zxvf redis-3.0.0.tar.gz

5,進入解壓目錄編譯ruby

make

6,安裝redis

 make install PREFIX=/usr/local/redis

2、啓動redis

1,從redis-3.0.0文件中複製redis-conf到redis的安裝目錄中
2,而後修改redis.conf文件

daemonize yes

3,在bin目錄下啓動redis

./bin/redis-server redis.conf

注意:redis默認佔用端口是6379 。

4,中止redis服務

./bin/redis-cli shutdown

5, 鏈接到 redis服務器

 使用如下命令鏈接到redis遠程服務器。

redis-cli -h 192.168.253.140 -p 6379

參數解釋:

-h  遠程redis服務器的IP地址。

-p  redis服務器對外開發的端口。

 

 遇到問題:

1,開啓遠程登陸鏈接。

從本地遠程鏈接CentOS 服務器上的Redis,一直報錯鏈接不成功。通過查詢資料,發現原來redis默認只能localhost登錄,因此須要開啓遠程登錄。解決方法以下:

1)在redis的配置文件redis.conf中,找到bind對應的項,將bind 127.0.0.1 改爲了bind 0.0.0.0 。表明着局域網內的全部計算機都能訪問。

若是redis服務器啓動了,先關閉它。

# 註釋掉原有的bind項目
#bind 127.0.0.1

bind 0.0.0.0

band localhost   只能本機訪問,局域網內計算機不能訪問。
bind  局域網IP    只能局域網內IP的機器訪問, 本地localhost都沒法訪問。
bind 0.0.0.0      表示本機和局域網內IP的機器都能訪問。

2)從新啓動redis服務,終於一切正常了,在本地鏈接上redis服務器後存儲數據name ,能夠在遠程服務器正常顯示。以下圖所示:

 

3、redis集羣的搭建

該集羣中有三個節點,每一個節點有一主一備。本來須要6臺虛擬機,可是爲了節省資源,能夠在一臺虛擬機上啓動6個redis實例。在此搭建一個僞分佈式的集羣,使用6個redis實例來模擬。向着目標前進吧,just do it 。

1,安裝ruby環境

yum install ruby
yum install rubygems

使用如下命令安裝ruby的redis的接口

gem install redis

若是返回如下錯誤信息,表示沒法安裝redis接口,由於沒法鏈接到gem服務器。

須要手工下載並安裝:

wget https://rubygems.global.ssl.fastly.net/gems/redis-3.2.1.gem
gem install -l ./redis-3.2.1.gem 

  還須要將redis集羣管理工具redis-trib.rb上傳至服務器。

2, 在/usr/local/redis目錄下建立cluster目錄

cd /usr/local/redis

mkdir cluster

 3,進入cluster目錄,建立如下目錄 7001,7002,7003,7004,7005,7006 。

cd /usr/local/redis/cluster
mkdir 7001
mkdir 7002
mkdir 7003
mkdir 7004
mkdir 7005
mkdir 7006

4,而後將/usr/local/redis/redis-3.*/redis.conf依次複製到7000 7002 7003 7004 7005 7006這6個目錄

 能夠參考如下命令完成操做。

cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7001
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7002
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7003
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7004
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7005
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7006

5,修改配置文件redis.conf

首先修改7001目錄文件下的redis.conf配置文件

vi /usr/local/redis/cluster/7001/redis.conf

 修改配置文件中的下面選項

port 7001
daemonize yes
cluster-enabled yes
cluster-config-file nodes7001.conf
cluster-node-timeout 5000
appendonly yes

一樣再對其它配置文件進行修改

vi /usr/local/redis/cluster/7002/redis.conf
vi /usr/local/redis/cluster/7003/redis.conf
vi /usr/local/redis/cluster/7004/redis.conf
vi /usr/local/redis/cluster/7005/redis.conf
vi /usr/local/redis/cluster/7006/redis.conf

注意:不一樣的目錄配置不一樣的redis.conf中的port,cluster-config-file值。

 6,啓動6個redis

cd /usr/local/redis
./bin/redis-server /usr/local/redis/cluster/7001/redis.conf
.
/bin/redis-server /usr/local/redis/cluster/7002/redis.conf
./bin/redis-server /usr/local/redis/cluster/7003/redis.conf
./bin/redis-server /usr/local/redis/cluster/7004/redis.conf
./bin/redis-server /usr/local/redis/cluster/7005/redis.conf
./bin/redis-server /usr/local/redis/cluster/7006/redis.conf

啓動以後使用命令查看redis的啓動狀況 ps -ef|grep redis 

[root@localhost redis]# ps -ef | grep redis
root     17243     1  0 13:25 ?        00:00:00 ./bin/redis-server 0.0.0.0:7001 [cluster]                  
root     17248     1  0 13:25 ?        00:00:00 ./bin/redis-server 0.0.0.0:7002 [cluster]                  
root     17256     1  0 13:26 ?        00:00:00 ./bin/redis-server 0.0.0.0:7003 [cluster]                  
root     17260     1  0 13:26 ?        00:00:00 ./bin/redis-server 0.0.0.0:7004 [cluster]                  
root     17264     1  0 13:26 ?        00:00:00 ./bin/redis-server 0.0.0.0:7005 [cluster]                  
root     17268     1  0 13:26 ?        00:00:00 ./bin/redis-server 0.0.0.0:7006 [cluster]                  
root     17275 17149  0 13:27 pts/0    00:00:00 grep redis
[root@localhost redis]#

看到以上信息說明都啓動成功。

7,建立redis集羣

cd /usr/local/redis

./redis-trib.rb create --replicas 1 192.168.253.140:7001 192.168.253.140:7002 192.168.253.140:7003 192.168.253.140:7004 192.168.253.140:7005 192.168.253.140:7006

命令的意義以下:
  給定 redis-trib.rb 程序的命令是 create , 這表示咱們但願建立一個新的集羣。
  選項 --replicas 1 表示咱們但願爲集羣中的每一個主節點建立一個從節點。
  以後跟着的其餘參數則是實例的地址列表, 咱們但願程序使用這些地址所指示的實例來建立新集羣。
  簡單來講, 以上命令的意思就是讓 redis-trib 程序建立一個包含三個主節點和三個從節點的集羣。

   若是redis實例配置正常的話,返回以下信息,成功生成redis集羣。注意:若是建立redis集羣失敗,只要把redis.conf中定義的 cluster-config-file 所在的文件刪除,從新啓動redis-server及運行redis-trib便可。

>>> Creating cluster
>>> Performing hash slots allocation on 6 nodes...
Using 3 masters:
127.0.0.1:7001
127.0.0.1:7002
127.0.0.1:7003
Adding replica 127.0.0.1:7004 to 127.0.0.1:7001
Adding replica 127.0.0.1:7005 to 127.0.0.1:7002
Adding replica 127.0.0.1:7006 to 127.0.0.1:7003
M: 98ce3e1be69335521e5928d82f7ea0214a751d2b 127.0.0.1:7001
   slots:0-5460 (5461 slots) master
M: f8856471eb35e874035d38c5bb54f2ff8987f665 127.0.0.1:7002
   slots:5461-10922 (5462 slots) master
M: 8ef8e2758c91327bc78f383e7303c0164fe47adb 127.0.0.1:7003
   slots:10923-16383 (5461 slots) master
S: 9a2ea466d8f3a4abac890ab752249e3eab0f4d74 127.0.0.1:7004
   replicates 98ce3e1be69335521e5928d82f7ea0214a751d2b
S: e960ae156a4942437ef9e4d6bc07b1b162eaa697 127.0.0.1:7005
   replicates f8856471eb35e874035d38c5bb54f2ff8987f665
S: 7a2046a101e338de2f78876b7798854e709a21fe 127.0.0.1:7006
   replicates 8ef8e2758c91327bc78f383e7303c0164fe47adb
Can I set the above configuration? (type 'yes' to accept): yes
>>> Nodes configuration updated
>>> Assign a different config epoch to each node
>>> Sending CLUSTER MEET messages to join the cluster
Waiting for the cluster to join....
>>> Performing Cluster Check (using node 127.0.0.1:7001)
M: 98ce3e1be69335521e5928d82f7ea0214a751d2b 127.0.0.1:7001
   slots:0-5460 (5461 slots) master
   1 additional replica(s)
S: e960ae156a4942437ef9e4d6bc07b1b162eaa697 127.0.0.1:7005
   slots: (0 slots) slave
   replicates f8856471eb35e874035d38c5bb54f2ff8987f665
S: 7a2046a101e338de2f78876b7798854e709a21fe 127.0.0.1:7006
   slots: (0 slots) slave
   replicates 8ef8e2758c91327bc78f383e7303c0164fe47adb
M: 8ef8e2758c91327bc78f383e7303c0164fe47adb 127.0.0.1:7003
   slots:10923-16383 (5461 slots) master
   1 additional replica(s)
M: f8856471eb35e874035d38c5bb54f2ff8987f665 127.0.0.1:7002
   slots:5461-10922 (5462 slots) master
   1 additional replica(s)
S: 9a2ea466d8f3a4abac890ab752249e3eab0f4d74 127.0.0.1:7004
   slots: (0 slots) slave
   replicates 98ce3e1be69335521e5928d82f7ea0214a751d2b
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.
[root@localhost redis]# 

至此集羣環境搭建成功了,遇到的問題終於解決了。: )

 

4、操做redis集羣

1, 使用 redis-cli命令進入集羣環境

使用redis-cli命令進入集羣,注意: 輸入redis-cli 命令時,附帶的參數 -c 不能省略,詳情看redis-cli的參考資料。

本地鏈接redis集羣例子

cd /usr/local/redis

./bin/redis-cli -c -p 7001

 遠程鏈接redis集羣 例子

redis-cli.exe -c -h 192.168.253.140 -p 7001

2, 中止集羣

cd /usr/local/redis

./bin/redis-cli redis-cli -p 7001 shutdown
./bin/redis-cli redis-cli -p 7002 shutdown
./bin/redis-cli redis-cli -p 7003 shutdown
./bin/redis-cli redis-cli -p 7004 shutdown
./bin/redis-cli redis-cli -p 7005 shutdown
./bin/redis-cli redis-cli -p 7006 shutdown

3,集羣重啓
有時候機器被重啓了,須要從新啓動集羣,只須要將6臺redis啓起來,集羣自動就會加載,恢復以前保存過的數據,不須要再次建立集羣。

5、Jedis操做redis集羣

1, example1

模擬的集羣環境.在一臺機器上啓動多個redis..每一個redis對應的是不一樣端口.在c192.168.253.140上啓動的....總共3主3從 端口號對應的的是7001~7006。

import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

public class TestCluster {
    @Test
    public void test1() throws Exception {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
        HostAndPort hostAndPort = new HostAndPort("192.168.253.140", 7000);
        HostAndPort hostAndPort1 = new HostAndPort("192.168.253.140", 7001);
        HostAndPort hostAndPort2 = new HostAndPort("192.168.253.140", 7002);
        HostAndPort hostAndPort3 = new HostAndPort("192.168.253.140", 7003);
        HostAndPort hostAndPort4 = new HostAndPort("192.168.253.140", 7004);
        HostAndPort hostAndPort5 = new HostAndPort("192.168.253.140", 7005);
        nodes.add(hostAndPort);
        nodes.add(hostAndPort1);
        nodes.add(hostAndPort2);
        nodes.add(hostAndPort3);
        nodes.add(hostAndPort4);
        nodes.add(hostAndPort5);
        JedisCluster jedisCluster = new JedisCluster(nodes, poolConfig);//JedisCluster中默認分裝好了鏈接池.
        //redis內部會建立鏈接池,從鏈接池中獲取鏈接使用,而後再把鏈接返回給鏈接池
        String string = jedisCluster.get("a");
        System.out.println(string);            
    }
}

 

6、使用redis-py-cluster模塊操做redis集羣

 使用python操做redis集羣,須要安裝redis-py-cluster模塊。使用如下命令安裝。

 pip install redis-py-cluster

 

2, 實例

from rediscluster import StrictRedisCluster
import sys

def redis_cluster():
    redis_nodes =  [{'host':'192.168.253.140','port':7001},
                    {'host':'192.168.253.140','port':7002},
                    {'host':'192.168.253.140','port':7003},
                    {'host':'192.168.253.140','port':7004},
                    {'host':'192.168.253.140','port':7005},
                    {'host':'192.168.253.140','port':7006}
                   ]
    try:
        redisconn = StrictRedisCluster(startup_nodes=redis_nodes)
    except Exception as msg :
        print(  msg )
        
    redisconn.set('name','admin')
    redisconn.set('age',18)
    print( "name is: ", redisconn.get('name') )
    print( "age  is: ", redisconn.get('age') )

    redisconn.flushdb()
   
redis_cluster()

 

 

 

總結:

  •     集羣中各臺機器的配置信息一致,Master/Slaver關係是在建立集羣時由系統分配
  •     redis集羣公用16384個slot,分配給不一樣的Master
  •     每一個key最終都會位於某一個slot,讀取key時會先轉向到某一個slot,而後讀取其中的值
  •     新增集羣或減小集羣(如新增或減小Master)會從新分配slot

 

補充資料:

1,Redis-cli使用時各參數的含義和使用方法

[root@localhost redis]# redis-cli --help
redis-cli 3.2.9

Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]
  -h <hostname>      Server hostname (default: 127.0.0.1).
  -p <port>          Server port (default: 6379).
  -s <socket>        Server socket (overrides hostname and port).
  -a <password>      Password to use when connecting to the server.
  -r <repeat>        Execute specified command N times.
  -i <interval>      When -r is used, waits <interval> seconds per command.
                     It is possible to specify sub-second times like -i 0.1.
  -n <db>            Database number.
  -x                 Read last argument from STDIN.
  -d <delimiter>     Multi-bulk delimiter in for raw formatting (default: \n).
  -c                 Enable cluster mode (follow -ASK and -MOVED redirections).
  --raw              Use raw formatting for replies (default when STDOUT is
                     not a tty).
  --no-raw           Force formatted output even when STDOUT is not a tty.
  --csv              Output in CSV format.
  --stat             Print rolling stats about server: mem, clients, ...
  --latency          Enter a special mode continuously sampling latency.
  --latency-history  Like --latency but tracking latency changes over time.
                     Default time interval is 15 sec. Change it using -i.
  --latency-dist     Shows latency as a spectrum, requires xterm 256 colors.
                     Default time interval is 1 sec. Change it using -i.
  --lru-test <keys>  Simulate a cache workload with an 80-20 distribution.
  --slave            Simulate a slave showing commands received from the master.
  --rdb <filename>   Transfer an RDB dump from remote server to local file.
  --pipe             Transfer raw Redis protocol from stdin to server.
  --pipe-timeout <n> In --pipe mode, abort with error if after sending all data.
                     no reply is received within <n> seconds.
                     Default timeout: 30. Use 0 to wait forever.
  --bigkeys          Sample Redis keys looking for big keys.
  --scan             List all keys using the SCAN command.
  --pattern <pat>    Useful with --scan to specify a SCAN pattern.
  --intrinsic-latency <sec> Run a test to measure intrinsic system latency.
                     The test will run for the specified amount of seconds.
  --eval <file>      Send an EVAL command using the Lua script at <file>.
  --ldb              Used with --eval enable the Redis Lua debugger.
  --ldb-sync-mode    Like --ldb but uses the synchronous Lua debugger, in
                     this mode the server is blocked and script changes are
                     are not rolled back from the server memory.
  --help             Output this help and exit.
  --version          Output version and exit.

Examples:
  cat /etc/passwd | redis-cli -x set mypasswd
  redis-cli get mypasswd
  redis-cli -r 100 lpush mylist x
  redis-cli -r 100 -i 1 info | grep used_memory_human:
  redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3
  redis-cli --scan --pattern '*:12345*'

  (Note: when using --eval the comma separates KEYS[] from ARGV[] items)

When no command is given, redis-cli starts in interactive mode.
Type "help" in interactive mode for information on available commands
and settings.

[root@localhost redis]# 

2,往redis中緩存數據的時候,它怎麼知道該緩存到哪一個服務器上呢??
  Redis 集羣中內置了16384 個哈希槽,搭建集羣時,每臺服務器上已經分配了固定的哈希槽編號。當須要在 Redis 集羣中放置一個key-value(數據) 時,redis 先對 key 使用 crc16 算法算出一個結果,而後把結果對 16384 求餘數,這樣每一個 key 都會對應一個編號在 0-16383 之間的哈希槽,redis 會根據求餘的結果,把數據映射到不一樣的redis服務器上。 

3,基本redis集羣的操做命令:
redis 127.0.0.1:6379> info #查看server版本內存使用鏈接等信息
redis 127.0.0.1:6379> client list #獲取客戶鏈接列表
redis 127.0.0.1:6379> client kill 127.0.0.1:33441 #終止某個客戶端鏈接
redis 127.0.0.1:6379> dbsize #當前保存key的數量
redis 127.0.0.1:6379> save #當即保存數據到硬盤
redis 127.0.0.1:6379> bgsave #異步保存數據到硬盤
redis 127.0.0.1:6379> flushdb #當前庫中移除全部key
redis 127.0.0.1:6379> flushall #移除全部key從全部庫中
redis 127.0.0.1:6379> lastsave #獲取上次成功保存到硬盤的unix時間戳
redis 127.0.0.1:6379> monitor #實時監測服務器接收到的請求
redis 127.0.0.1:6379> slowlog len #查詢慢查詢日誌條數
redis 127.0.0.1:6379> slowlog get #返回全部的慢查詢日誌,最大值取決於slowlog-max-len配置
redis 127.0.0.1:6379> slowlog get 2 #打印兩條慢查詢日誌
redis 127.0.0.1:6379> slowlog reset #清空慢查詢日誌信息

更詳細的命令請參考官網:http://redisdoc.com/
中文網站:http://www.redis.cn/commands.html

 

參考資料:
http://www.redis.cn/topics/cluster-tutorial.html
http://blog.csdn.net/myrainblues/article/details/25881535/
http://www.cnblogs.com/wuxl360/p/5920330.html
http://blog.csdn.net/yfkiss/article/details/38944179
http://diaocow.iteye.com/blog/1938032
http://www.cnblogs.com/guxiong/p/6270140.html
http://blog.csdn.net/ziele_008/article/details/51829429
centos配置ruby開發環境
https://my.oschina.net/u/1449160/blog/260764

http://www.cnblogs.com/gossip/p/5993401.html 

java

http://blog.csdn.net/junlong750/article/details/51362423

http://www.cnblogs.com/huali/p/5810054.html

使用強大的可視化工具redislive來監控咱們的redis

http://www.cnblogs.com/huangxincheng/archive/2016/06/08/5571185.html

理論知識:

http://www.cnblogs.com/wxd0108/p/5798498.html

redis集羣密碼設置

http://blog.csdn.net/jtbrian/article/details/53691540 

相關文章
相關標籤/搜索