[java] ActiveMQ와 메시지 질의 언어 (MQTT)

개요

ActiveMQ는 Apache 소프트웨어 재단에 의해 개발된 오픈소스 메시지 브로커입니다. 최근에는 IoT (Internet of Things) 애플리케이션에서 많이 사용되고 있는 MQTT (Message Queuing Telemetry Transport) 프로토콜을 지원합니다. 이번 블로그 포스트에서는 ActiveMQ와 MQTT를 사용하여 메시지를 보내고 받는 방법에 대해 알아보겠습니다.

ActiveMQ 설정

먼저, ActiveMQ를 설치하고 설정하는 방법을 알아보겠습니다.

  1. ActiveMQ 홈페이지에서 최신 버전을 다운로드합니다.
  2. 다운로드한 파일을 압축 해제한 뒤, ActiveMQ를 실행시킬 수 있는 디렉토리로 이동합니다.
  3. bin 디렉토리에서 activemq start 명령어를 실행하여 ActiveMQ를 시작합니다.
  4. 웹 브라우저에서 http://localhost:8161 로 접속하여 ActiveMQ 웹 콘솔에 접속합니다.
  5. 콘솔에서 새로운 큐를 생성하고 구성합니다.

MQTT 메시지 보내기

이제 ActiveMQ를 사용하여 MQTT 메시지를 보내는 방법에 대해 알아보겠습니다.

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttPublisher {

    public static void main(String[] args) {
        String topic = "myTopic";
        String content = "Hello, MQTT!";
        int qos = 2;
        String broker = "tcp://localhost:1883";
        String clientId = "publisher";

        try {
            MqttClient mqttClient = new MqttClient(broker, clientId);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            mqttClient.connect(connOpts);

            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            mqttClient.publish(topic, message);

            mqttClient.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

위의 예제는 Eclipse Paho MQTT 라이브러리를 사용하여 ActiveMQ에 MQTT 메시지를 보내는 간단한 코드입니다. 코드를 실행하면 “myTopic” 주제에 “Hello, MQTT!” 라는 메시지가 발행됩니다.

MQTT 메시지 수신

이제 ActiveMQ를 사용하여 MQTT 메시지를 수신하는 방법에 대해 알아보겠습니다.

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttSubscriber {

    public static void main(String[] args) {
        String topic = "myTopic";
        int qos = 2;
        String broker = "tcp://localhost:1883";
        String clientId = "subscriber";

        try {
            MqttClient mqttClient = new MqttClient(broker, clientId);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            mqttClient.connect(connOpts);

            mqttClient.subscribe(topic, qos);

            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("Received message: " + new String(message.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

위의 예제는 ActiveMQ에서 MQTT 메시지를 수신하는 간단한 코드입니다. 코드를 실행하면 “myTopic” 주제의 메시지가 도착할 때마다 메시지 내용이 출력됩니다.

결론

이번 포스트에서는 ActiveMQ와 MQTT를 사용하여 메시지를 보내고 받는 방법을 알아보았습니다. ActiveMQ는 다양한 애플리케이션 간에 데이터를 교환하기 위한 강력한 메시징 시스템이며, MQTT는 경량화되어 있는 메시지 프로토콜로 IoT 애플리케이션에서 널리 사용됩니다. ActiveMQ와 MQTT를 결합하여 신속하고 효율적인 메시지 통신을 구현할 수 있습니다.


참고: