栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot + eclipse paho 实现mqtt client 消费者

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot + eclipse paho 实现mqtt client 消费者

目录
  • 依赖
  • 配置
  • 回调类
  • 创建消费者
  • 启动


依赖
		
            org.springframework.boot
            spring-boot-starter-integration
        

        
            org.springframework.integration
            spring-integration-stream
        

        
            org.springframework.integration
            spring-integration-mqtt
        
配置

yml文件

  mqtt:
    username: 用户名
    password: 密码
    host: mqtt服务器地址
    client-id: 唯一的client-id
    topic: 要订阅的主题
    connection-timeout: 30
    keep-alive-interval: 10
    qos: 0

property类

@Component
@ConfigurationProperties(prefix = "mqtt")
@Data
public class MqttProperty {

    private String username;

    private String password;

    private String host;

    private String clientId;

    private String topic;

    private Integer connectionTimeout;

    private Integer keepAliveInterval;

    private Integer qos;

}
回调类
@Configuration
@Slf4j
public class MyCallBack implements MqttCallback {
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("mqtt链接丢失");
    }

    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        log.info("topic:" + s);
        String data = new String(mqttMessage.getPayload());
        log.info("message:" + data);
        
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.debug("deliveryComplete:" + iMqttDeliveryToken.isComplete());
    }
}
创建消费者
@Configuration
@Slf4j
public class ClientBuilder {
    @Resource
    MqttProperty mqttProperty;

    @Resource
    MyCallBack myCallBack;

    @Bean
    public MqttClient init() throws MqttException {
        MqttClient ret = new MqttClient(mqttProperty.getHost(), mqttProperty.getClientId());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(mqttProperty.getUsername());
        options.setPassword(mqttProperty.getPassword().toCharArray());
        options.setCleanSession(false);
        options.setConnectionTimeout(mqttProperty.getConnectionTimeout());
        options.setKeepAliveInterval(mqttProperty.getKeepAliveInterval());
        options.setAutomaticReconnect(true);
        ret.setCallback(myCallBack);
        ret.connect(options);
        if (!ret.isConnected()){
            log.info("mqtt链接"+ mqttProperty.getHost() +"失败");
        }
        else {
            log.info("mqtt链接"+ mqttProperty.getHost() +"成功");
            ret.subscribe(mqttProperty.getTopic(), mqttProperty.getQos());
        }
        return ret;
    }
}

启动

启动项目后会自动订订阅配置的主题

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/306610.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号