3.6版本
This commit is contained in:
@@ -16,6 +16,7 @@ const CFG = {
|
||||
};
|
||||
|
||||
let conn = null;
|
||||
let connectionLock = null; // 🔒 连接锁,防止并发创建
|
||||
let pubCh = null; // 发布 Confirm Channel
|
||||
let conCh = null; // 消费 Channel
|
||||
const emitter = new EventEmitter();
|
||||
@@ -37,54 +38,80 @@ function toBuffer(payload) {
|
||||
|
||||
// —— 内部:建立连接(含心跳、keepalive、事件)
|
||||
async function createConnection() {
|
||||
const connection = await amqp.connect({
|
||||
protocol: CFG.protocol,
|
||||
hostname: CFG.host,
|
||||
port: CFG.port,
|
||||
username: CFG.user,
|
||||
password: CFG.pass,
|
||||
vhost: CFG.vhost,
|
||||
heartbeat: CFG.heartbeat,
|
||||
frameMax: CFG.frameMax > 0 ? CFG.frameMax : undefined,
|
||||
// 也可用 URL 形式:`amqp://u:p@host:5672/vhost?heartbeat=60`
|
||||
});
|
||||
// 1. 如果已有连接,直接返回
|
||||
if (conn) return conn;
|
||||
|
||||
// 打开 TCP keepalive,降低 NAT/空闲超时断开的概率
|
||||
try {
|
||||
const stream = connection.stream || connection.socket;
|
||||
if (stream?.setKeepAlive) stream.setKeepAlive(true, 15_000); // 15s
|
||||
} catch (_) { }
|
||||
// 2. 如果正在连接中,等待它完成
|
||||
if (connectionLock) {
|
||||
return connectionLock;
|
||||
}
|
||||
|
||||
connection.on('error', (e) => {
|
||||
// 心跳超时常见,避免重复噪音
|
||||
const msg = e?.message || String(e);
|
||||
if (msg && /heartbeat/i.test(msg)) {
|
||||
console.error('[AMQP] 连接错误 (心跳):', msg);
|
||||
} else {
|
||||
console.error('[AMQP] 连接错误:', msg);
|
||||
// 3. 开始新连接,加锁
|
||||
connectionLock = (async () => {
|
||||
try {
|
||||
console.log(`[AMQP] 开始连接 ${CFG.host}...`);
|
||||
const connection = await amqp.connect({
|
||||
protocol: CFG.protocol,
|
||||
hostname: CFG.host,
|
||||
port: CFG.port,
|
||||
username: CFG.user,
|
||||
password: CFG.pass,
|
||||
vhost: CFG.vhost,
|
||||
heartbeat: CFG.heartbeat,
|
||||
frameMax: CFG.frameMax > 0 ? CFG.frameMax : undefined,
|
||||
});
|
||||
|
||||
// 如果在连接过程中被要求关闭(race condition),则立刻关闭并抛错
|
||||
if (closing) {
|
||||
console.warn('[AMQP] 连接刚建立但 Detected closing=true, closing now...');
|
||||
connection.close().catch(() => { });
|
||||
throw new Error('Connection aborted (closing)');
|
||||
}
|
||||
|
||||
// 打开 TCP keepalive
|
||||
try {
|
||||
const stream = connection.stream || connection.socket;
|
||||
if (stream?.setKeepAlive) stream.setKeepAlive(true, 15_000);
|
||||
} catch (_) { }
|
||||
|
||||
connection.on('error', (e) => {
|
||||
const msg = e?.message || String(e);
|
||||
if (msg && /heartbeat/i.test(msg)) {
|
||||
console.error('[AMQP] 连接错误 (心跳):', msg);
|
||||
} else {
|
||||
console.error('[AMQP] 连接错误:', msg);
|
||||
}
|
||||
emitter.emit('error', e);
|
||||
});
|
||||
|
||||
connection.on('close', () => {
|
||||
if (closing) return;
|
||||
console.error('[AMQP] 连接已关闭');
|
||||
conn = null; pubCh = null; conCh = null;
|
||||
scheduleReconnect();
|
||||
});
|
||||
|
||||
connection.on('blocked', (reason) => {
|
||||
console.warn('[AMQP] 连接被代理阻塞::', reason);
|
||||
emitter.emit('blocked', reason);
|
||||
});
|
||||
connection.on('unblocked', () => {
|
||||
console.log('[AMQP] 链接解锁');
|
||||
emitter.emit('unblocked');
|
||||
});
|
||||
|
||||
console.log(`[AMQP] 已连接到 ${CFG.host} (hb=${CFG.heartbeat}s)`);
|
||||
conn = connection; // ✅ 赋值给全局变量
|
||||
return connection;
|
||||
} catch (err) {
|
||||
console.error('[AMQP] createConnection failed:', err.message);
|
||||
throw err;
|
||||
} finally {
|
||||
connectionLock = null; // 🔓 解锁
|
||||
}
|
||||
emitter.emit('error', e);
|
||||
});
|
||||
})();
|
||||
|
||||
connection.on('close', () => {
|
||||
if (closing) return; // 正在关闭时不重连
|
||||
console.error('[AMQP] 连接已关闭');
|
||||
conn = null; pubCh = null; conCh = null;
|
||||
scheduleReconnect();
|
||||
});
|
||||
|
||||
// Broker 侧内存/磁盘压力会 block 连接
|
||||
connection.on('blocked', (reason) => {
|
||||
console.warn('[AMQP] 连接被代理阻塞::', reason);
|
||||
emitter.emit('blocked', reason);
|
||||
});
|
||||
connection.on('unblocked', () => {
|
||||
console.log('[AMQP] 链接解锁');
|
||||
emitter.emit('unblocked');
|
||||
});
|
||||
|
||||
console.log(`[AMQP] 已连接到 ${CFG.host} (hb=${CFG.heartbeat}s)`);
|
||||
return connection;
|
||||
return connectionLock;
|
||||
}
|
||||
|
||||
// —— 内部:确保连接和通道存在
|
||||
@@ -252,6 +279,7 @@ async function publishToExchange(exchange, routingKey, payload, options = {}) {
|
||||
persistent = true,
|
||||
headers = {},
|
||||
mandatory = false,
|
||||
// mandatory = false,
|
||||
} = options;
|
||||
|
||||
if (assertExchange) {
|
||||
@@ -267,6 +295,9 @@ async function publishToExchange(exchange, routingKey, payload, options = {}) {
|
||||
async function reconnectNow() {
|
||||
if (closing) return;
|
||||
if (reconnecting) return;
|
||||
// 如果正在连接,也视为正在重连/忙碌,稍后
|
||||
if (connectionLock) return;
|
||||
|
||||
try {
|
||||
if (pubCh) await pubCh.close().catch(() => { });
|
||||
if (conCh) await conCh.close().catch(() => { });
|
||||
@@ -281,6 +312,18 @@ async function reconnectNow() {
|
||||
async function close() {
|
||||
closing = true;
|
||||
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
||||
|
||||
// 关键修复:如果正在建立连接,必须等待它完成(或失败),再执行关闭
|
||||
// 否则 amqplib 的 "socket closed abruptly" 错误会频发
|
||||
if (connectionLock) {
|
||||
try {
|
||||
console.log('[AMQP] close() called while connecting, waiting...');
|
||||
await connectionLock;
|
||||
} catch (_) {
|
||||
// 忽略连接失败
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// 取消所有消费者
|
||||
for (const [q, c] of consumers.entries()) {
|
||||
@@ -298,6 +341,14 @@ async function close() {
|
||||
}
|
||||
|
||||
// —— 进程信号(可选)
|
||||
async function open() {
|
||||
closing = false;
|
||||
reconnecting = false;
|
||||
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
||||
backoff = 1000;
|
||||
await ensureChannels();
|
||||
}
|
||||
|
||||
process.once('SIGINT', async () => { try { await close(); } finally { process.exit(0); } });
|
||||
process.once('SIGTERM', async () => { try { await close(); } finally { process.exit(0); } });
|
||||
|
||||
@@ -305,6 +356,7 @@ module.exports = {
|
||||
startConsumer,
|
||||
publishToQueue,
|
||||
publishToExchange,
|
||||
open,
|
||||
reconnectNow,
|
||||
close,
|
||||
emitter, // 可订阅 'message' / 'handlerError' / 'reconnected' / 'error' / 'blocked' / 'unblocked'
|
||||
|
||||
Reference in New Issue
Block a user