기술, 개발/RabbitMQ

Queue and Exchange

Jaejin Sim 2025. 9. 10. 23:01
반응형

1. Queue 생성

queue_declare()

  • 큐가 존재하지 않으면 큐를 생성한다
// hello 라는 이름의 큐 선언
/*
name: 큐 이름 (hello)
passive: false
durable: true // the queue will survive server restarts
exclusive: false // the queue can be accessed in other channels
auto_delete: false //the queue won't be deleted once the channel is closed.
*/
$channel->queue_declare('hello', false, false, false, false);

 

인수  설명  비고
name 큐 이름 amq로 시작하는 큐 이름은 생성 할 수 없다
passive true : hello 라는 큐가 있으면 Queue.declare_ok 없으면 오류
false : hello 라는 큐가 없으면 생성해줌
 
durable ture : RabbitMQ 서버가 다시 시작 되도 큐는 살아있음
false : 서버가 죽으면 큐도 삭제됨
 
exclusive true : 독점 큐 선언 (임시 큐)
프로세스 (프로듀서, 컨슈머)가 종료되면 큐 삭제됨
독립적인 큐 혼자 쓸 건지
프로듀서는 단발성으로 프로세스가 바로 종료 되기때문에

독점 큐 선언은 컨슈머에서 선언해야함
auto_delete true : 컨슈머의 채널이 닫혔을 때 큐 삭제됨
false : 컨슈머의 채널이 닫혀도 큐는 삭제 안됨
 
  • 큐 이름이 빈 값 이면 이름을 자동으로 생성함. ex)amq.gen-JzTY20BRgKO-HjmUJj0wLg
  • 최초 실행하면 RabbitMQ에 hello 라는 큐가 없기 때문에 큐를 먼저 생성해줍니다.
  • 어드민에서 hello 라는 큐가 생성된 걸 볼 수 있음

참고!!

// 처음에 아래와 같이 hello 큐를 생성
$channel->queue_declare('hello', false, false, false, false);

// 만약 옵션 값을 변경 한다면 ??
$channel->queue_declare('hello', false, true, false, false); // 오류 발생!!!

이미 hello 라는 큐가 있어서 오류 발생함.
이럴 때는 큐이름을 변경 하던가, 어드민에서 hello 큐를 삭제 해야 함

2. exchange 선언 (생성)

exchange_declare()

/*
    name: $exchange
    type: direct
    passive: false
    durable: true // the exchange will survive server restarts
    auto_delete: false //the exchange won't be deleted once the channel is closed.
*/
$channel->exchange_declare('Route', AMQPExchangeType::DIRECT, false, true, true);

 

인수  설명
name exchange 이름
type 4개의 타입이 있음
passive true : exchange (name)가 없으면 예외 발생. 있으면 아무것도 하지 않음
false : 없으면 새로 선언
durable ture : RabbitMQ 서버가 다시 시작 되도 exchange 는 살아있음
false : 서버가 죽으면 exchange 도 삭제됨
auto_delete true : 해당 큐에 대한 바인딩이 끊기고 해당 큐를 참조 하는 컨슈머의 채널이 닫히면 exchange 는 삭제됨
해당 큐에 대한 바인딩만 끊겨도 exchange는 삭제됨
큐 auto_delete = true 해줘야 역할을 제대로 할 수 있음
(어드민에서 수동으로 바인딩을 끊지 않으면 해당 exchange 는 계속 살아있음)

3. 큐 바인딩

// 인수에 대한 설명은 생략합니다.
$channel->queue_bind($queue_name, $exchange_name, $route_key);
  • basic_publish() 에서 직접 큐로 연결이 안되고 exchange 를 사용 해야 한다
  • queue_bind() 를 사용하여 queue와 exchange 를 연결
  • 프로듀서에서 메세지를 전달 할 때 큐로 도달하기 위한 통로 개념으로 이해하면 될 듯?

$route_key

  • exchange direct 타입 사용 시 이용되고 route_key 를 지정할 경우 basic_publish() 에서 지정한 route_key ****를 넣어야 메세지가 큐에 도달함
$channel->queue_declare("hello", false, false, true, false);
$channel->queue_bind('hello', 'direct_logs','route_test_key');
$channel->exchange_declare('direct_logs', 'direct', false, false, false);
$channel->basic_publish($msg, 'direct_logs', 'route_test_key');
반응형