redis集群搭建


Table of Contents

参考资料

Redis 集群是一个提供在多个Redis间节点间共享数据的程序集

准备

集群开始需要运行redis集群实例,而且要让集群正常运作至少需要三个主节点,这里创建六个节点,三个为主节点,三个为从节点,端口号分别为9001,9002,9003,9004,9005,9006

并创建六个以端口号为名字的目录, 在每个目录中运行一个Redis实例

mkdir -p redis/9001
cd redis
mkdir 9002
mkdir 9003
mkdir 9004
mkdir 9005
mkdir 9006

然后将对应的配置redis.conf放入相应的目录中(记得修改端口号)

最小配置选项:

port 9001
cluster-enabled yes
cluster-config-file node9001.conf
cluster-node-timeout 5000
appendonly yes

然后就可以启动redis实例了

redis-server redis/9001/redis.conf
redis-server redis/9002/redis.conf
redis-server redis/9003/redis.conf
redis-server redis/9004/redis.conf
redis-server redis/9005/redis.conf
redis-server redis/9006/redis.conf

由于这个过程很简单而且重复,所以我写了一个脚本进行创建:

@cli.command()
@click.option('--dirs', '-d', default=DEFAULT_PATH)
@click.option('--port', '-p', default=9001)
def create(dirs, port):
    for i in range(6):
        path = os.path.join(dirs, str(port + i))
        if not os.path.exists(path):
            os.makedirs(path)
        conf = os.path.join(path, 'redis.conf')
        with open(conf, 'w+') as f:
            text = '''port {0}
cluster-enabled yes
cluster-config-file nodes{0}.conf
cluster-node-timeout 5000
appendonly yes
'''.format(port + i)
            f.write(text)
        with cd(dirs):
            os.system('redis-server {}'.format(conf))

创建集群

使用redis的官方脚本redis-trib进行创建

ruby redis-trib.rb create --replicas 1 127.0.0.1:9001 127.0.0.1:9002 127.0.0.1:9003 127.0.0.1:9004 127.0.0.1:9005 127.0.0.1:9006

或者接上面的脚本

ports = ['127.0.0.1:{}'.format(port + i) for i in range(6)]
os.system('ruby redis-trib.rb create --replicas 1 {}'.format(' '.join(
    ports)))

–replicas 1:表示为集群中的每个主节点创建一个从节点

结果如图所示:

输入yes 最后查看集群是否启动成功

测试集群

-c 选项以集群方式启动

$ redis-cli -c -p 7000
  127.0.0.1:9001> keys *
  (empty list or set)
  127.0.0.1:9001> set hello world
  OK
  127.0.0.1:9001> get hello
  "world"
  127.0.0.1:9001> set hello1 world1
  -> Redirected to slot [11613] located at 127.0.0.1:9003
  OK
  127.0.0.1:9003> get hello1
  "world1"
  127.0.0.1:9003> set hello2 world2
  -> Redirected to slot [7486] located at 127.0.0.1:9002
  OK
  127.0.0.1:9002> get hello2
  "world2"

进入另一个实例

$ redis-cli -c -p 9002
  127.0.0.1:9002> get hello
  -> Redirected to slot [866] located at 127.0.0.1:9001
  "world"
  127.0.0.1:9001> get hello1
  -> Redirected to slot [11613] located at 127.0.0.1:9003
  "world1"
  127.0.0.1:9003> get hello2
  -> Redirected to slot [7486] located at 127.0.0.1:9002
  "world2"

ok,先这样

作者: honmaple
链接: https://honmaple.me/articles/2017/08/redis集群搭建.html
版权: CC BY-NC-SA 4.0 知识共享署名-非商业性使用-相同方式共享4.0国际许可协议
wechat
alipay

加载评论