Publisher / Subscriber

Category
스터디노트 Redis
Status
Published
Tags
Redis
Description
Published
Slug
Redis의 Pub/Sub(발행/구독) 모델은 메시지를 특정 수신자에게 직접 전달하지 않고, 여러 수신자에게 메시지를 전송할 수 있는 구조.
이는 뉴스 알림, 실시간 데이터 스트리밍, 채팅 애플리케이션 등에서 유용하게 쓰임. Pub/Sub에서는 메시지를 전달하지만 저장하지 않으며, 각 구독자는 구독 신청한 채널에 대해 수신할 수 있음
 

Pub/Sub 예제 코드 설명

Redis Pub/Sub 예제는 publishersubscriber라는 두 개의 Redis 클라이언트를 통해 메시지를 발행하고 구독하는 구조를 보여줌
const redis = require('redis'); const subscriber = redis.createClient(); const publisher = redis.createClient(); let msg_count = 0;
 
이 코드에서는 subscriberpublisher라는 두 개의 Redis 클라이언트 객체를 생성하고, 구독 및 메시지 발행을 시작함
  1. subscriber.on('subscribe', callback): 구독이 시작되었을 때 호출됨.
    1. 여기서는 구독이 시작된 후에 publisher가 메시지를 발행하도록 설정
      subscriber.on('subscribe', function (channel, count) { publisher.publish('Goorm Channel', '발행자 첫번째 메시지'); publisher.publish('Goorm Channel', '발행자 두번째 메시지'); publisher.publish('Goorm Channel', '발행자 마지막 메시지'); });
       
  1. subscriber.on('message', callback): subscriber가 메시지를 수신할 때 호출됨. 메시지를 수신할 때마다 채널명과 메시지를 출력하고, 메시지 수(msg_count)를 증가시
    1. subscriber.on('message', function (channel, message) { console.log('채널명: ' + channel + ', 메시지: ' + message); msg_count += 1; if (msg_count == 3) { subscriber.unsubscribe(); // 구독 종료 subscriber.end(); publisher.end(); } });
      이 예제에서는 3개의 메시지를 수신하면 subscriberpublisher가 연결을 종료하도록 설정
       
  1. subscriber.subscribe('Goorm Channel'): 구독을 시작.
    1. "Goorm Channel"이라는 채널을 구독하므로, 이 채널로 발행되는 메시지를 subscriber가 수신하게 됨

 

실행 결과

코드를 실행하면 아래와 같은 출력이 나타남
채널명: Goorm Channel, 메시지: 발행자 첫번째 메시지 채널명: Goorm Channel, 메시지: 발행자 두번째 메시지 채널명: Goorm Channel, 메시지: 발행자 마지막 메시지
위에서, subscriber"Goorm Channel" 채널을 구독하고,
publisher가 발행한 세 개의 메시지를 차례로 수신하여 출력