[java] Apache ActiveMQ와 MQTT 프로토콜의 사용

Apache ActiveMQ는 Java로 구현된 오픈 소스 메시징 브로커입니다. MQTT (Message Queuing Telemetry Transport)는 경량 메시징 프로토콜로, IoT (Internet of Things) 애플리케이션에서 많이 사용됩니다.

ActiveMQ는 MQTT 프로토콜을 지원하기 때문에, MQTT를 활용하여 메시지 브로커와 클라이언트 간에 효율적으로 메시지를 교환할 수 있습니다. 이를 통해 IoT 기기들과 통신할 수 있으며, 작은 대역폭을 사용하여 실시간 데이터 전송을 지원합니다.

MQTT 프로토콜의 특징

ActiveMQ에서 MQTT 사용하기

ActiveMQ는 MQTT 트랜스포터를 통해 MQTT 클라이언트와 통신할 수 있습니다. 다음은 ActiveMQ를 통해 MQTT를 사용하는 예제 코드입니다.

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class MQTTExample {
    public static void main(String[] args) {
        String brokerUrl = "tcp://localhost:61616";
        String topic = "myTopic";

        try {
            // 1. ActiveMQ 연결 설정
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
            Connection connection = connectionFactory.createConnection();
            connection.start();

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

            // 3. 목적지(Topic) 생성
            Destination destination = session.createTopic(topic);

            // 4. 메시지 송수신을 위한 Producer, Consumer 생성
            MessageConsumer consumer = session.createConsumer(destination);
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        if (message instanceof TextMessage) {
                            String text = ((TextMessage) message).getText();
                            System.out.println("Received message: " + text);
                        }
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });

            MessageProducer producer = session.createProducer(destination);

            // 5. 메시지 발행
            TextMessage textMessage = session.createTextMessage("Hello, MQTT!");
            producer.send(textMessage);

            // 6. 연결 종료
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

위 예제 코드에서는 ActiveMQ를 사용하여 “myTopic”이라는 주제에 “Hello, MQTT!”라는 메시지를 발행하는 예제입니다. 해당 주제를 구독한 클라이언트는 메시지를 받아 활용할 수 있습니다.

ActiveMQ는 MQTT 프로토콜을 통해 다양한 IoT 애플리케이션에 적합한 메시징 솔루션을 제공합니다. MQTT의 경량성과 내결함성을 활용하여 안정적인 IoT 통신을 구축할 수 있습니다.

참고 자료