Java连接Mqtt

引入依赖

 <dependency>
     <groupId>org.eclipse.paho</groupId>
      <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
       <version>1.2.5</version>
 </dependency>
mqtt配置类
import lombok.Data;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;


@Component
@Configuration
@Data
public class MqttConfiguration {

    String broker = "tcp://xxx.xxx.x.xx:1883";    //默认用tcp去接
    String username = "账号";
    String password = "密码";

    @Bean
    public void getMqttCustomerClient() {
        String topic = "订阅主题";
        String clientid = "mqttx_42dfb39b";   保证唯一就行
        int qos = 0;
        try {
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            // 连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            client.connect(options);
            // 设置回调
            client.subscribe(topic, qos);
            client.setCallback(new MqttCallback() {
                public void connectionLost(Throwable cause) {
                        try {
                            client.connect();
                        } catch (MqttException e) {
                            throw new RuntimeException(e);
                        }
                        System.out.println("connectionLost: " + cause.getMessage());
                    }
                    public void messageArrived(String topic, MqttMessage message) {
                        System.out.println("topic: " + topic);   //主题
                        System.out.println("Qos: " + message.getQos());//Qos
                        System.out.println("message content: " + new String(message.getPayload()));  //订阅消息内容

                    }
                    public void deliveryComplete(IMqttDeliveryToken token) {
                        System.out.println("deliveryComplete---------" + token.isComplete());
                    }
                });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//需要订阅多个 弄多个Bean就可以
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值