MQTT - subscribe 시 retained data 받아오기 (how to set subscribe) [spring boot]

2025. 1. 25. 22:16·Back-end/spring boot
728x90

MQTTv5 에서는 내가 알던 기능보다 다양한 부분이 있었다.

 

Retained Data

retained data는 mqtt에서 retained (유지한) 값을 그 topic에 맞게 저장하는 개념이다.

즉, retained를 지정해서 publish를 해놓으면 그 후에 해당 topic에 subscribe를 하면 바로 마지막에 publish된 값을 받을 수 있다.


gradle

// https://mvnrepository.com/artifact/org.eclipse.paho/org.eclipse.paho.mqttv5.client
implementation("org.eclipse.paho:org.eclipse.paho.mqttv5.client:1.2.5")

 

publish

// publish는.. 까먹음  
// publish( topic 명, 전달할 메시지, qos, retained 한다면 1/안하면 0)
client.publish("topic","message",1,1);

 

subscribe

import org.eclipse.paho.mqttv5.client.IMqttMessageListener;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.MqttSubscription;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

@Configuration
public class MqttConfig {

    private final String broker = "tcp://localhost:1883"; // mqtt broker 설정
    private final String clientId = "client";
    private final String TOPIC = "test";
    private final int connectTimeout = 1000;
    private final int keepAlive = 30;

    private MqttClient mqttClient;
    private final MqttMessageHandler mqttMessageHandler;

    public MqttConfig(MqttMessageHandler mqttMessageHandler) {
        this.mqttMessageHandler = mqttMessageHandler;
    }

    @Bean
    public MqttConnectionOptions mqttConnectionOptions() {
        MqttConnectionOptions options = new MqttConnectionOptions();
        options.setServerURIs(new String[]{broker});
        options.setAutomaticReconnect(true);
        options.setConnectionTimeout(connectTimeout);
        options.setKeepAliveInterval(keepAlive);
        options.setCleanStart(false); // false해야 retained 됨
        return options;
    }

    @Bean(destroyMethod = "")
    public MqttClient mqttClient() {
        try {
            mqttClient = new MqttClient(broker, clientId, new MemoryPersistence());
            mqttClient.connect(mqttConnectionOptions());

            mqttClient.subscribe(RESPONSE_TOPIC,1);

            // Subscription 설정
            MqttSubscription subscription = new MqttSubscription(TOPIC, 1);
            subscription.setRetainHandling(1); // 1: 구독 시 retained 메시지 수신

            // 구독 수행
            mqttClient.subscribe(new MqttSubscription[]{subscription}, new IMqttMessageListener[] {
                new IMqttMessageListener() {
                    @Override
                    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                        // 여기서 바로 subscribe된 후에 retained 값 있으면 가져와서 처리해줘야 함
                        String message = new String(mqttMessage.getPayload());
                    }
                }
            });

            return mqttClient;
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    @PreDestroy
    public void close() {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.disconnect();
                mqttClient.close();
            }
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }
}

 

 


publish하는 법은 인터넷에서 많이 나와있지만 subscribe하는 방법은 알기가 어려워서 cursor를 통해 subscribe를 할 수 있었다.

 

고마워 따봉 커서야.

 

728x90
반응형

'Back-end > spring boot' 카테고리의 다른 글

Webclient 외부 API 통신 - java [spring boot]  (1) 2025.01.27
MQTT - response topic 설정 후 publish까지 (reponse - request) [spring boot]  (1) 2025.01.26
@Scheduled는 이전 작업이 끝나기 전에 다음 작업이 실행되지 않는다. (cron, fixedRate, fixedDelay든 상관없이) @Scheduled does not run the next task before the previous task completes. [spring boot]  (0) 2024.08.15
PSQLException 예외처리 - getCause()와 getSQLState() 활용해 DB 연결, data insert 예외처리 | PSQLException exception handling - DB connection and data insertion using getCause() and getSQLState() [spring boot]  (0) 2024.08.15
Jpa 삭제된 데이터의 개수 확인하기 + log로 표시 | Jpa Check the number of deleted data + display as log [spring boot]  (0) 2024.08.14
'Back-end/spring boot' 카테고리의 다른 글
  • Webclient 외부 API 통신 - java [spring boot]
  • MQTT - response topic 설정 후 publish까지 (reponse - request) [spring boot]
  • @Scheduled는 이전 작업이 끝나기 전에 다음 작업이 실행되지 않는다. (cron, fixedRate, fixedDelay든 상관없이) @Scheduled does not run the next task before the previous task completes. [spring boot]
  • PSQLException 예외처리 - getCause()와 getSQLState() 활용해 DB 연결, data insert 예외처리 | PSQLException exception handling - DB connection and data insertion using getCause() and getSQLState() [spring boot]
은성이
은성이
    250x250
  • 은성이
    은성의 블로그
    은성이
  • 전체
    오늘
    어제
    • 분류 전체보기 (85) N
      • Front-end (8)
        • html (2)
        • css (3)
        • Vue.js (2)
        • React.js (1)
      • Back-end (10)
        • Node-js (1)
        • spring boot (9)
      • Side project (2)
        • mistake (1)
        • 잊어버렸던 것 (0)
      • Programming language (14)
        • javascript (3)
        • Java (10)
        • C (1)
        • Jsp (0)
      • App (1)
        • Android studio (1)
      • Database (3)
        • MySQL (2)
        • SQL (1)
      • git (6)
      • IoT (6)
        • Arduino (4)
        • 라즈베리파이 (1)
      • Adobe (0)
        • Photoshop (0)
        • Illustrator (0)
      • NFT (1)
      • Metaverse (1)
        • gather town (1)
      • 일상 (10) N
        • 독서 reading (2)
        • 강연 (3)
        • 현장실습 (3)
      • 언어 (10)
        • 영어 (10)
        • 일본어 (0)
      • IT (1)
        • linux (1)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    css
    개발
    자바
    생활코딩
    백엔드
    영어복습
    개발자
    GIT
    프로젝트
    일상
    깃공부
    영어공부
    코딩
    코딩공부
    html
    화상영어
    springboot
    java
    영어
    공부
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
은성이
MQTT - subscribe 시 retained data 받아오기 (how to set subscribe) [spring boot]
상단으로

티스토리툴바