.env 配置连接
REDIS_DB=[{"host":"10.0.11.10","port":6379},{"host":"10.0.11.10","port":6378},{"host":"10.0.11.11","port":6379},{"host":"10.0.11.10","port":6378}]
使用ioredis库进行连接
import Redis from 'ioredis';
//创建集群连接
let redis;
const redisConfig = process.env.REDIS_DB;
if (redisConfig) {
const redisNodes = JSON.parse(redisConfig);
const prefix = `${process.env.REDIS_PREFIX || 'nc_'}`;
//多于一个节点,创建集群连接
if (redisNodes.length > 1) {
redis = new Redis.Cluster(redisNodes, {
redisOptions: {
password: null,
}
});
}
// 如果只配置一个,那么认为是单节点连接
else if (redisNodes.length === 1) {
redis = new Redis(`redis://${redisNodes[0].host}:${redisNodes[0].port}/0`, {
keyPrefix: prefix,
});
} else {
throw ('redis 配置错误')
}
} else {
throw ('redis 配置错误')
}
Cluster配置项
redisOptions:{
db:Number,
keyPrefix:String,
password:String
.
.
.
}
等等,可以转到Cluster的定义看。