배씨의 개발일지

실시간 채팅 - 캐시 메모리 저장 후 DB 저장하기 본문

TIL

실시간 채팅 - 캐시 메모리 저장 후 DB 저장하기

용찬 2023. 8. 31. 20:25

기존의 실시간 채팅 (웹 소켓 이용, mongoDB바로 저장)을
일정시간 캐시메모리에 저장 후 분기별로 mongoDB에 저장 하는 방식을 사용해볼것이다.



  // 메시지를 캐시에 저장하는 메서드
  private cacheMessage(roomId: number, message: any): void {
    if (!this.messageCache[roomId]) {
      this.messageCache[roomId] = [];
    }
    this.messageCache[roomId].push(message);
  }

메시지를 캐시에 저장하는 메서드

 // MongoDB에 채팅 데이터 저장
  private async flushCacheToMongoDB() {
    try {
      // MongoDB에 연결
      const chatCollection = this.mongoClient
        .db('chat_logs')
        .collection('chats');
      // 모든 방의 메시지를 캐시에서 가져와서 MongoDB에 저장
      for (const room of Object.keys(this.messageCache)) {
        const messages = this.messageCache[room];

        if (messages.length > 0) {
          // 캐시된 메시지를 MongoDB에 저장
          await chatCollection.insertMany(messages);
          // 캐시를 비웁니다.
          this.messageCache[room] = [];
          console.log(`Cache flushed to MongoDB for room: ${room}`);
        }
      }
    } catch (error) {
      console.error('Error flushing cache to MongoDB:', error);
    }
  }

캐시메모리에 있는 데이터를 DB에 저장하는 메서드

// 스케줄러 설정 메서드
  private setUpScheduler() {
    // 30분마다 flushCacheToMongoDB 메서드를 호출하도록 스케줄러 설정
    setInterval(() => {
      this.flushCacheToMongoDB();
    }, 10 * 60 * 1000); // 10분 간격으로 실행 (밀리초 단위)
  }

캐시메모리에 있는 데이터를 DB로 옮겨 줄 주기를 설정해주는 메서드

이렇게 메서드를 생성 후 기존의 DB에 저장하는 로직이 있는 부분에서 메서드를 호출해주면 된다.

@WebSocketGateway()
@Injectable()
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  private mongoClient: MongoClient;
  private messageCache: { [room: string]: any[] } = {};

  constructor(
    @InjectRepository(Access) private accessRepository: Repository<Access>,
    private readonly socketGuard: SocketGuard,
    private readonly groupService: GroupService,
  ) {
    const mongoOptions: MongoClientOptions = {};

    this.mongoClient = new MongoClient(
      'mongodb://127.0.0.1:27017/chat_log',
      mongoOptions,
    );
    this.mongoClient.connect().then(() => {
      this.setUpScheduler();
      this.flushCacheToMongoDB();
    });
    this.setUpScheduler();
  }

연결은 connect().the(()=>{
메서드 호출
)
이러한 방식으로 해주었다.

Comments