Redis Cluster 搭建

我的 blog: iyuhp.top
原文连接: Redis Cluster 集群搭建html

关于 redis 集群,通常有如下几种模式node

  • 主从复制模式(Master-Slave) : 该模式下,全部的事务操做,都会异步同步到其余 slave 上,每台 redis 都存储相同数据
  • 哨兵模式(Sentinel) : 经过增长 sentinel 集群,管理 master-slave 下的节点,能够在 master 宕机时,选举新的 master 节点
  • Jedis sharding :在客户端,对 key 进行 hash ,散列到不一样的 redis 实例上
  • 相关中间件如 codis , twemproxy 等

在 redis 3.0 版本其,官方提供了 redis cluster 功能。git

redis cluster 简介

redis cluster 主要基于 CRC16 算法对 key 进行 hash ,而后散列到不一样散列槽。github

redis cluster 总共提供 16384 个hash 槽(slot) ,理论上,集群的最大节点数量最大乐意为 16384 个。不过 redis 官方给出的建议是不要超过 1000 的量级。redis

每一个 redis instance 会负责这个散列槽中的一部分。算法

新增删除节点,对于 redis cluster 而言就是对 slot 进行 reshard,redis cluster 保证 slot 平滑移动bash

1. key hash 计算

redis cluster 会对大括号 {} 中的值计算 hash 值进行散列。异步

  • 只计算第一次出现 {} 的值,若是没有,则计算整个 key 的 hash 值, 如
    • key{key1}{key2} : 值计算 key1 的hash
    • keykey : 计算整个 keykey 的 hash
  • 若是只有 { ,没有 } ,或者 {} 中没有内容,则计算整个 key 的 hash 值, 如
    • key{12 : 计算整个 hash
    • key{}key : 计算整个 hash,这意味着全部以 {} 开头的 key ,都是整个计算 hash

源码以下:工具

unsigned int keyHashSlot(char *key, int keylen) {
    int s, e; /* start-end indexes of { and } */

    for (s = 0; s < keylen; s++)
        if (key[s] == '{') break;

    /* No '{' ? Hash the whole key. This is the base case. */
    if (s == keylen) return crc16(key,keylen) & 0x3FFF;

    /* '{' found? Check if we have the corresponding '}'. */
    for (e = s+1; e < keylen; e++)
        if (key[e] == '}') break;

    /* No '}' or nothing between {} ? Hash the whole key. */
    if (e == keylen || e == s+1) return crc16(key,keylen) & 0x3FFF;

    /* If we are here there is both a { and a } on its right. Hash * what is in the middle between { and }. */
    return crc16(key+s+1,e-s-1) & 0x3FFF;
}
复制代码

2. 集群拓扑结构

redis cluster 是一个网状拓扑结构,每一个 redis instance ,都会与其余 redis instance 创建链接,也就是说若是集群中有 n 个节点,则总共会有 n(n-1) 个链接,这些 TCP 链接会被永久保存,并不是按需建立。ui

redis cluster struct

3. 集群工做

client 发送请求 ,集群中某个节点接收到请求后,会查找内部 slot , node id 映射,若是是本身,执行命令返回结果,若是是其余节点,则会给 client 返回一个 MOVED slot_id target_ip:port 的错误。客户端须要根据返回的节点信息,再次执行命令。

注意,若是在此期间,目标节点出现故障,slot 发生了转移,则 client 仍须要根据返回的 ip:port 再次查询

redis cluster 搭建

1. 安装 redis

wget https://github.com/antirez/redis/archive/5.0.7.tar.gz
tar -xvf ./5.0.7.tar.gz
复制代码

下载并解压后,你能够 make 一把,但你经过上面下载后,其实在 src 包里已经有可使用的 redis server 等各个工具,能够直接使用。

Redis Github 上的安装步骤很详细,这里再也不赘述

ps: 我是由于 make 以后跑 make test 时,一直挂掉,由于我内存实在过小... 因此就直接用了

2. 编辑配置文件

# 该集群阶段的端口
port 7000
# 是否后台启动
daemonize yes
# 我没有内存,这里设置 50m
maxmemory 50m

# 为每个集群节点指定一个 pid_file
pidfile /home/dylan/tmp/scripts-redis/cluster/pid/pid_7000.pid

#在bind指令后添加本机的ip
bind 127.0.0.1

####################################### file #######################
loglevel notice
logfile /home/dylan/tmp/scripts-redis/cluster/log/log_7000.log
dbfilename "dump.rdb"
dir "/home/dylan/tmp/scripts-redis/cluster/data/7000"

#################################### cluster ####################################
cluster-enabled yes # 启用集群模式
# 集群的配置,配置文件首次启动自动生成 , 不能人工编辑,是集群节点自动维护的文件
cluster-config-file "/home/dylan/tmp/scripts-redis/cluster/config/nodes_7000.conf"
cluster-node-timeout 5000

# 配置后,经过 cli 链接须要经过 -a 123456 链接
requirepass "123456"
masterauth "123456"
复制代码

3. 复制多份配置文件并修改对应值

redis cluster folder

如图所示,将 redis.conf 配置文件 copy 6 份(由于 redis 要求最少 3 master ,咱们要每一个 master 一个 slave ,那么这里就须要 6 个实例),而后建好 conf 文件里配置的各个目录

4. 启动 redis 实例

redis-server redis.conf ,这个命令想必你们都很熟悉,这里就再也不啰嗦。这里咱们只须要依次启动 6 个实例便可。

我我的写了个小脚本,后面会贴上来。

5. 建立集群

redis 提供了 cluster create 命令帮助咱们建立 redis cluster

redis-cli -a 123456 --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 --cluster-replicas 1
复制代码

执行该命令后,会有以下输出:

redis create cluster

经过 redis 输出的信息能看到,如今是 3 master 3 slave,每一个 master 一个 slave 节点

6. 查看集群信息

# 注意 -c 参数,表示以集群方式登入
redis-cli -a 123456 -c -p 7000
复制代码

cluster 相关的命令,请参考 这里

这个时候咱们 set 几个数据:

127.0.0.1:7000> set a a
-> Redirected to slot [15495] located at 127.0.0.1:7002
OK
127.0.0.1:7002> set b b
-> Redirected to slot [3300] located at 127.0.0.1:7000
OK
127.0.0.1:7000> keys *
1) "b"
复制代码

能够看到,第一次 set a 时, 被路由到了 7002 节点,第二次 set b 时,路由到了 7000 也就是本身这儿,经过 keys * (请不要在生产环境使用该命令) 查看时, 只有 key b (kb...) , key a 不会显示,由于它在 7002 节点那儿

小脚本

没有作多少重构,将就着用...

./run.sh start all : 分别以 conf 目录下的配置文件启动 redis 实例

./run.sh stop all : 中止全部 conf 目录下配置文件产生的 redis 实例

./run.sh cluster : 在启动全部 redis 实例后,经过 cluster 命令建立集群,须要手动修改 ip:port

./run.sh status : 查看 redis 实例,这里没有提供查看单个 redis 实例 status 的方法

#!/usr/bin/env bash 
# redis server / redis cli 所在目录
workdir="/home/dylan/tmp/redis-5.0.8/src"
# 脚本所在目录
scriptdir="/home/dylan/tmp/scripts-redis"
# cluster 各个目录
cluster_dir="${scriptdir}/cluster"
cluster_pid_dir="${cluster_dir}/pid"
cluster_conf_dir="${cluster_dir}/conf"

# $1 is redis config file name looks like ./conf/redis.1234.conf
# return pid file name looks like pid_1234.pid
function get_redis_pid_file(){
        rport=$(echo "$1" | awk -F"." '{print $(NF-1)}')
        echo -e "${cluster_pid_dir}/pid_$rport.pid"
}

function get_redis_conf_file() {
        conf=$(echo "$1" | awk -F"/" '{print $NF}')
        echo -e "${cluster_conf_dir}/$conf"
}

# $1 should be redis config file name looks like redis.1234.conf
function redis_start(){
        # conf file looks like redis.port.conf
        # pid file looks like pid_port.pid
        redis_conf_path=$1
        redis_conf=$(get_redis_conf_file ${redis_conf_path})
        redis_conf_path_forshow="Redis with config $(echo ${redis_conf} | awk -F"/" '{print $NF}')"
        pidfile=$(get_redis_pid_file ${redis_conf_path})

        if [ -f $pidfile ]; then
                if kill -0 `cat $pidfile` > /dev/null 2>&1; then
                        echo REDIS already running as process `cat $pidfile`.
                        return
                fi
        fi
        # 配置中已经配置了 daemonize yes
        # nohup ${workdir}/redis-server $conffile > $logfile 2>&1 < /dev/null &
        ${workdir}/redis-server $redis_conf
        if [ $? -eq 0 ]; then
                sleep 1
                if [ -f $pidfile ]; then
                        pid=$(cat $pidfile)
                        if ps -p $pid > /dev/null 2>&1; then
                                echo ${redis_conf_path_forshow} STARTED
                        else
                                echo ${redis_conf_path_forshow} FAILED TO START
                                exit 1
                        fi
                else
                        echo ${redis_conf_path_forshow} start failed
                        exit 1
                fi
        else
                echo ${redis_conf_path_forshow} DID NOT START
                exit 1
        fi

}

conffile=$2
case $1 in
        start)
                # 若是 $2 为 all ,则启动全部
                if [ "all" == "$conffile" ]; then
                        echo "Run all files in $cluster_conf"
                        for rfile in ${cluster_conf_dir}/*.conf
                        do
                                redis_start $rfile
                                if [ $? -ne 0 ]; then
                                        exit 1
                                fi
                        done
                elif [ ! -f "$conffile" ]; then # 输入的文件不存在
                        echo Can not find $conffile.
                        exit 1
                elif [ -z $conffile ]; then
                        redis_start $conffile
                else
                        echo "Usage $0 start (all|redis_config_file)"
                        exit 1
                fi
                exit 0
                ;;
        stop)
                if [ "all" == "$conffile" ]; then
                        echo Stopping all...
                        for rfile in ${cluster_conf_dir}/*.conf
                        do
                                pid=$(get_redis_pid_file $rfile)
                                if [ ! -f "$pid" ]; then
                                        echo
                                        echo Redis with config "$rfile" already stopped
                                        continue
                                fi
                                kill `cat $pid`
                                sleep 1
                                echo
                                echo Redis with config $rfile STOPPED
                        done
                elif [ ! -f "$conffile" ]; then
                        echo Can not find $conffile.
                        exit 1
                elif [ -f $conffile ]; then
                        pid=$(get_redis_pid_file $rfile)
                        kill `cat $pid`
                        sleep 1
                        echo STOPPED
                else
                        echo "Usage $0 stop (all|redis_config_file)"
                        exit 1
                fi
                ;;
        status)
                echo "Checking status..."
                echo Found `ls ${cluster_conf_dir} | wc -l` config file
                echo
                for rfile in ${cluster_conf_dir}/*.conf
                do
                        pid=$(get_redis_pid_file $rfile)
                        if [ -f $pid ]; then
                                if [ ! -s ${pid} ]; then
                                        echo file $pid is empty. skip...
                                        echo "Please check $pid."
                                        echo
                                        continue
                                fi
                                if ps -p `cat $pid` > /dev/null 2>&1;then
                                        echo REDIS $pid with pid `cat $pid` is running
                                else
                                        echo "Not running with pid `cat $pid`, Please check it"
                                        exit 1
                                fi
                        else
                                echo "Not running with config file $rfile. No pid file exists."
                        fi
                done
                ;;

        cluster)
                echo "Start clusting..."
                ${workdir}/redis-cli -a 123456 --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 --cluster-replicas 1
                exit 0
                ;;
        test)
                echo
                echo "Test Success"
                exit 0
                ;;
        *)
                echo
                echo -n "Usage: "
                echo -n "$0 status or "
                echo "$0 {start|stop} conf_file_path" >&2
                ;;
esac
复制代码
相关文章
相关标签/搜索