redis集群及fastify框架下如何使用redis集群

使用redis-cli对redis进行集群操作

1、安装新版本redis

yum install -y http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

yum --enablerepo=remi install redis -y

2、配置多实例

由于redis cluster最低要求是3个主节点,每个主节点还需要一个从节点,所以需要6个实例,如需要集群认证,带上命令-a passwd

复制5份redis.conf文件,修改后的端口分别为6380~6384,6380单个配置如下:

port 6380
bind 0.0.0.0
requirepass test
masterauth test
cluster-enabled yes
cluster-config-file nodes-6380.conf
pidfile /var/run/redis_6382.pid
logfile /var/log/redis/redis_6382.log
dbfilename dump_6382.rdb
daemonize yes

修改其余文件相应配置即可

3、启动服务

/usr/bin/redis-server /etc/redis.conf
/usr/bin/redis-server /etc/redis_6380.conf
/usr/bin/redis-server /etc/redis_6381.conf
/usr/bin/redis-server /etc/redis_6382.conf
/usr/bin/redis-server /etc/redis_6383.conf
/usr/bin/redis-server /etc/redis_6384.conf

4、创建集群主节点,此步骤可以跳过到第5步

redis-cli  -a test --cluster create 192.168.10.12:6379 192.168.10.12:6380 192.168.10.12:6381

5、创建集群主从节点

redis-cli  -a test --cluster create 192.168.10.12:6379 192.168.10.12:6380 192.168.10.12:6381 192.168.10.12:6382 192.168.10.12:6383 192.168.10.12:6384 --cluster-replicas 1

--cluster-replicas 参数为数字,1表示每个主节点需要1个从节点,

6、到此集群创建完毕

7、使用npm ioredis进行集群的连接,安装ioredis

npm i ioredis

8、fastify下的使用

const fastify = require('fastify')({
        // logger: {level: 'trace'},
        ignoreTrailingSlash: false,
        caseSensitive: true,
        trustProxy: true,
    }),
    Redis=require('ioredis')
const client=new Redis.Cluster(
    [
        {
            host:'192.168.10.12',
            port:6379,
            password:'test'
        },
        {
            host:'192.168.10.12',
            port:6380,
            password:'test'
        }, {
            host:'192.168.10.12',
            port:6381,
            password:'test'
        }, {
            host:'192.168.10.12',
            port:6382,
            password:'test'
        }, {
            host:'192.168.10.12',
            port:6383,
            password:'test'
        }, {
            host:'192.168.10.12',
            port:6384,
            password:'test'
        },
    ]
);
fastify.register(require('fastify-redis'),{client:client})
fastify.addHook('preHandler', (request, reply, next) => {
  request.redis=fastify.redis;
})

集群连接成功,其它数据获取参数fastify-redis相关命令即可

集群清除数据,连接到每个master节点上进行数据删除,每个master节点输入命令:flushall

你可能感兴趣的:(redis,nodejs)