| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- ipfs singletone
- java 파티
- 백준 특정한 최단 경로
- Spring ipfs
- 안정해시
- 익명 객체 @transactional
- rabbitmq 싱글톤
- ipfs bean
- java 1238
- kotiln const
- go
- kotiln const val
- spring mongoTemplate switch
- java 1509
- spring mongodb
- 백준 연결요소 자바
- kotiln functional interface
- java 백준 1509
- nodejs rabbitmq
- mongodb lookup
- 자바 1676
- Java Call By Refernce
- spring mongodb switch
- javav 1676
- 백준 1504 java
- Claude Intelij 연결
- spring mongoTemplate
- 백준 2252 줄세우기
- 자바 백준 팩토리얼 개수
- java 팩토리얼 개수
Archives
- Today
- Total
공부 흔적남기기
Node.js RabbitMq 싱글톤 적용하기 본문
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
반응형