redis集群
安装依赖:
npm i ioredis -S
创建 db/redis.js 文件
const IORedis = require('ioredis');
const redisClient = new IORedis.Cluster([
{"host": "127.0.0.1", "port": 6379, "password": "******", "db": 1},
{"host": "127.0.0.1", "port": 6380, "password": ""******",", "db": 1},
{"host": "127.0.0.1", "port": 6381, "password": ""******",", "db": 1}
]);
redisClient.on('ready', () => {
console.log('redisClient 连接成功');
});
redisClient.on('error', (error) => {
console.error('redisClient 连接错误:', error);
});
module.exports = redisClient;
入口文件引入
app.js
const redisClient = require('./db/redis');
结合 connect-redis 使用
安装依赖:
npm i express-session connect-redis -S
app.js
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const redisClient = require('./db/redis');
app.use(session({
name: 'xxx', // 自定义
secret: 'xxx', // 自定义
resave: true,
saveUninitialized: true,
cookie: {
httpOnly: true,
secure: false,
maxAge: 1000 * 60 * 60 * 24 // 一天
},
store: new RedisStore({client: redisClient})
}));
rabbimq集群
安装依赖
npm i amqplib -S
创建 rabbitmq.js 文件
const amqp = require('amqplib');
const clusterRabbitmq = [
"127.0.0.1:5673",
"127.0.0.1:5674",
"127.0.0.1:5675"
]
const rmqConfig = {
"user": "admin",
"pwd": "******",
"virtualhost": "/test"
}
let rmqConnection = null;
const length = clusterRabbitmq.length;
const rabbitmqConnect = async () => {
for(let i=0; i<length; i++) {
try {
rmqConnection = await amqp.connect(`amqp://${encodeURIComponent(rmqConfig.user)}:${encodeURIComponent(rmqConfig.pwd)}@${clusterRabbitmq[i]}/${rmqConfig.virtualhost}?heartbeat=5`);
break;
} catch(err) {
console.error(`Failed to connect to ${clusterRabbitmq[i]}`);
}
}
rmqConnection.on("error", function(e) {
// ...
})
rmqConnection.on("close", function() {
// ...
})
}
rabbitmqConnect()