web study/Node.js
Node.js RabbitMq 싱글톤 적용하기
65살까지 코딩
2023. 7. 7. 09:00
728x90
반응형
node.js 에서 rabbitmq를 사용하는데 매번 message가 보내질때마다
connection이 생기고 channel이 생기는게 너무 비효율적이라고 생각 들어서
싱글톤으로 구현함
import * as amqp from 'amqplib/callback_api';
import {URL} from 'url';
export interface Config {
url: string;
username: string;
password: string;
}
export class RabbitMq {
private connection: amqp.Connection | null
private channel: amqp.Channel | null
private config: Config;
constructor(config: Config) {
this.config = config;
this.connection = null;
this.channel = null;
}
private async getConnection(): Promise<amqp.Connection> {
return new Promise<amqp.Connection>( (resolve, reject) => {
if (this.connection) {
resolve(this.connection);
} else {
const parsedUrl = new URL(this.config.url);
const vhost = (parsedUrl.pathname.length > 1) ? parsedUrl.pathname : undefined;
amqp.connect(this.config.url, {
hostname: parsedUrl.hostname,
vhost: vhost,
port: parsedUrl.port ? parseInt(parsedUrl.port) : 5672,
username: this.config.username,
password: this.config.password
}, (error: Error, connection: any) => {
if (error) {
reject();
} else {
this.connection = connection;
resolve(connection);
}
});
}
});
}
private async getChannel(): Promise<amqp.Channel> {
return new Promise<amqp.Channel>( (resolve, reject) => {
if (this.channel) {
resolve(this.channel);
} else {
this.getConnection().then(
(connection) => {
connection.createChannel(async (error: Error, channel: any) => {
if (error) {
reject();
} else {
this.channel = channel;
resolve(channel);
}
});
}
).catch(() => reject());
}
});
}
public publishMessage(message: Object) {
this.getChannel().then(
(channel) => {
channel.publish('exchangeName', 'queueName', Buffer.from(JSON.stringify(message)));
}
).catch(() => console.log('Failed to establish RabbitMQ'));
}
}
2023-12-05 와서 생각해보니 stateless하게 connection을 만들고 끊는게 오히려 좋을 것 같다는 생각도 들었다..
728x90
반응형