redis集群搭建


参考资料

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

准备

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

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

1mkdir -p redis/9001
2cd redis
3mkdir 9002
4mkdir 9003
5mkdir 9004
6mkdir 9005
7mkdir 9006

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

最小配置选项:

1port 9001
2cluster-enabled yes
3cluster-config-file node9001.conf
4cluster-node-timeout 5000
5appendonly yes

然后就可以启动redis实例了

1redis-server redis/9001/redis.conf
2redis-server redis/9002/redis.conf
3redis-server redis/9003/redis.conf
4redis-server redis/9004/redis.conf
5redis-server redis/9005/redis.conf
6redis-server redis/9006/redis.conf

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

 1@cli.command()
 2@click.option('--dirs', '-d', default=DEFAULT_PATH)
 3@click.option('--port', '-p', default=9001)
 4def create(dirs, port):
 5    for i in range(6):
 6        path = os.path.join(dirs, str(port + i))
 7        if not os.path.exists(path):
 8            os.makedirs(path)
 9        conf = os.path.join(path, 'redis.conf')
10        with open(conf, 'w+') as f:
11            text = '''port {0}
12cluster-enabled yes
13cluster-config-file nodes{0}.conf
14cluster-node-timeout 5000
15appendonly yes
16'''.format(port + i)
17            f.write(text)
18        with cd(dirs):
19            os.system('redis-server {}'.format(conf))

创建集群

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

1ruby 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

或者接上面的脚本

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

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

结果如图所示:

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

测试集群

-c 选项以集群方式启动

 1$ redis-cli -c -p 7000
 2  127.0.0.1:9001> keys *
 3  (empty list or set)
 4  127.0.0.1:9001> set hello world
 5  OK
 6  127.0.0.1:9001> get hello
 7  "world"
 8  127.0.0.1:9001> set hello1 world1
 9  -> Redirected to slot [11613] located at 127.0.0.1:9003
10  OK
11  127.0.0.1:9003> get hello1
12  "world1"
13  127.0.0.1:9003> set hello2 world2
14  -> Redirected to slot [7486] located at 127.0.0.1:9002
15  OK
16  127.0.0.1:9002> get hello2
17  "world2"

进入另一个实例

 1$ redis-cli -c -p 9002
 2  127.0.0.1:9002> get hello
 3  -> Redirected to slot [866] located at 127.0.0.1:9001
 4  "world"
 5  127.0.0.1:9001> get hello1
 6  -> Redirected to slot [11613] located at 127.0.0.1:9003
 7  "world1"
 8  127.0.0.1:9003> get hello2
 9  -> Redirected to slot [7486] located at 127.0.0.1:9002
10  "world2"

ok,先这样

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

加载评论