[java] ActiveMQ와 RabbitMQ의 실습 예제

ActiveMQ와 RabbitMQ는 둘 다 매우 강력한 오픈 소스 메시지 브로커이며, 메시지 큐 기반의 메시징 시스템을 구축하는 데에 사용됩니다. 이들은 대규모 시스템에서 실시간 이벤트 처리, 메시지 전달, 태스크 관리 등의 용도로 많이 사용됩니다.

이번 실습에서는 ActiveMQ와 RabbitMQ를 사용하여 간단한 프로듀서(Producer)와 컨슈머(Consumer)를 구현해 보겠습니다.

ActiveMQ 실습 예제

개발 환경 설정

  1. ActiveMQ 설치: ActiveMQ 공식 홈페이지에서 ActiveMQ 브로커를 다운로드하고 설치합니다.
  2. Java 프로젝트 생성: IDE에서 Maven 프로젝트를 생성하고, pom.xml에 ActiveMQ 의존성을 추가합니다.

    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-all</artifactId>
        <version>{version}</version>
    </dependency>
    

프로듀서 작성하기

import javax.jms.*;

public class Producer {

    public static void main(String[] args) throws JMSException {
        // ActiveMQ 연결 설정
        ConnectionFactory connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = connectionFactory.createConnection();
        connection.start();

        // 세션 생성
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // 메시지 큐 설정
        Queue queue = session.createQueue("my_queue");

        // 메시지 전송
        MessageProducer producer = session.createProducer(queue);
        TextMessage message = session.createTextMessage("Hello, ActiveMQ!");
        producer.send(message);

        // 연결 종료
        connection.close();
    }
}

컨슈머 작성하기

import javax.jms.*;

public class Consumer {

    public static void main(String[] args) throws JMSException {
        // ActiveMQ 연결 설정
        ConnectionFactory connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = connectionFactory.createConnection();
        connection.start();

        // 세션 생성
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // 메시지 큐 설정
        Queue queue = session.createQueue("my_queue");

        // 메시지 수신
        MessageConsumer consumer = session.createConsumer(queue);
        Message message = consumer.receive();
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("Received message: " + textMessage.getText());
        }

        // 연결 종료
        connection.close();
    }
}

RabbitMQ 실습 예제

개발 환경 설정

  1. RabbitMQ 설치: RabbitMQ 공식 홈페이지에서 RabbitMQ 브로커를 다운로드하고 설치합니다.
  2. Java 프로젝트 생성: IDE에서 Maven 프로젝트를 생성하고, pom.xml에 RabbitMQ 의존성을 추가합니다.

    <dependency>
        <groupId>com.rabbitmq</groupId>
        <artifactId>amqp-client</artifactId>
        <version>{version}</version>
    </dependency>
    

프로듀서 작성하기

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;

public class Producer {

    private final static String QUEUE_NAME = "my_queue";

    public static void main(String[] args) throws Exception {
        // RabbitMQ 연결 설정
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 큐 선언
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 메시지 전송
        String message = "Hello, RabbitMQ!";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
        System.out.println("Sent message: " + message);

        // 연결 종료
        channel.close();
        connection.close();
    }
}

컨슈머 작성하기

import com.rabbitmq.client.*;

public class Consumer {

    private final static String QUEUE_NAME = "my_queue";

    public static void main(String[] args) throws Exception {
        // RabbitMQ 연결 설정
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 큐 선언
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 메시지 수신 콜백
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("Received message: " + message);
        };

        // 메시지 소비
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});

        // 무한 대기
        Thread.sleep(Long.MAX_VALUE);

        // 연결 종료
        channel.close();
        connection.close();
    }
}

위의 예제 코드를 실행하면 ActiveMQ나 RabbitMQ로 메시지를 보내고 받을 수 있습니다. 이를 통해 메시지 큐 기반의 메시징 시스템을 구현할 수 있습니다.

참고 자료: