개발환경

MqttClient 구현 ( eclipse paho v3)

toogari 2024. 7. 1. 15:12

mqttClient 구현시 주의 사항

1. automaticReconnect를 true로 처리함.

MqttConnectOptions option = new MqttConnectOptions();
option.setCleanSession(false);  // 재접속 성공시에 세션정보를 날리지 않음. (비즈니스에 맞게 처리)
option.setAutomaticReconnect(true);

2. 처음 접속할 때 mqtt 서버가 내려가 있을 수도 있으니 올라올 때까지 재접속 시도

boolean isConnected = false;
while (isConnected == false) {
    try {
        // try connection
        IMqttToken iMqttToken = client.connectWithResult(options);
        iMqttToken.waitForCompletion();

        // before topic subscribe
        client.subscribe(topic);
        log.info("subscribe topic : " + topic);

        isConnected = true;

        log.info("connected mqtt");

    } catch (MqttException e) {
        isConnected = false;

        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }

        log.info("retry connection...");
    }
}

 

3. mqtt 서버가 운영도중에 내려가고 올라올 때 처리하는 로직은 connectionLost 에서 처리하고 쓰레드로 처리해야 할 수도 있음에 유의

    @Override
    public void connectionLost(Throwable arg0) {
        log.error(arg0.getMessage(), arg0);
//        checkReconnect(this.topicToSubscribe);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("checkReconnect thread start..");
                    while (client.isConnected() == false) {
                        Thread.sleep(1000);
                    }
                    client.subscribe(topicToSubscribe);
                } catch (Exception e) {
                    log.error("subscribe "+e.getMessage());
                }
            }
        }).start();
    }