如何用代码实现发送MQTT消息
admin
2023-02-20 05:20:03
0

MQTT协议因低延迟、效率高在工业物联网领域使用的频率特别高,前面两篇文档分别对MQTT内容和MQTT服务器做了简单介绍,今天本文从实战的角度阐述如何用代码实现发送MQTT消息。


1.引入相关的依赖



org.springframework.boot
spring-boot-starter-web


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


org.springframework.integration
spring-integration-mqtt


2.在application.yml配置MQTT服务器信息


server:
  port: 9090
mqtt:
  host: tcp://127.0.0.1:1883
  clientinid: mqttinId
  clientoutid: mqttoutid
  topic: virus
  qoslevel: 1
  #MQTT 认证
  username:  xxx
  password: yyy
  # 10s
  timeout: 10000
  #20s
  keepalive: 20


3.配置MQTT消息推送配置


@Configuration
@IntegrationComponentScan
public class MqttSenderConfig {
    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    @Value("${mqtt.host}")
    private String hostUrl;
    @Value("${mqtt.clientinid}")
    private String clientId;
    @Value("${mqtt.topic}")
    private String defaultTopic;
    @Value("${mqtt.timeout}")
    private int completionTimeout;
    @Bean
    public MqttConnectOptions getMqttConnectOptions(){
        MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setConnectionTimeout(10);
        mqttConnectOptions.setKeepAliveInterval(90);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setKeepAliveInterval(2);
        return mqttConnectOptions;
    }
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler =  new MqttPahoMessageHandler(clientId, mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(defaultTopic);
        return messageHandler;
    }
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }
}


4.MQTT消息推送接口


@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttGateway {
    void sendToMqtt(String data, @Header(MqttHeaders.TOPIC) String topic);
}


5.MQTT消息推送API


@RestController
public class MessageController {
    @Autowired
    MqttGateway mqttGateway;
    @RequestMapping("/sendMqttMessage")
    public String sendMqttMessage(String message, String topic) {
        mqttGateway.sendToMqtt(message, topic);
        return "ok";
    }
}


测试


接下来就可以在POSTMAN中进行测试了,输入消息内容和主题,就可以在相应的频道发送消息了。如果使用其它的消息客户端进行测试的话,可以接受到消息

相关内容

热门资讯

石化油服获得实用新型专利授权:... 证券之星消息,根据天眼查APP数据显示石化油服(600871)新获得一项实用新型专利授权,专利名为“...
服务六大场景 机器人公园上岗 玉渊潭公园投用水面割草机器人。(刘平 摄) 天坛公园的智能巡护机器人上岗。(刘平 摄) 盛夏七月,...
力箭一号遥十五运载火箭圆满完成... 红星新闻网7月24日讯2026年7月24日07时33分,我国在东风商业航天创新试验区使用力箭一号遥十...
特朗普:美方正与伊朗谈判,不排... 当地时间7月24日,美国总统特朗普在白宫谈及对伊朗战争的“退出战略”时表示,美国有两种选择:一是继续...
小伙相亲2天后花33万闪婚,一... 极目新闻记者 邓波2025年4月,安徽安庆小伙何攀到贵州贵阳花果园相亲,并与相识两天的贵阳籍女子陆某...
丘成桐:王虹和邓煜都在MIT待... 当地时间7月23日,在美国费城举行的2026年国际数学家大会开幕式上,中国数学家邓煜、王虹获得菲尔兹...
欧盟对俄制裁列单中企,中国驻欧... 问:2026年7月23日,欧盟通过第21轮对俄罗斯制裁方案,新增列单制裁中国企业。中方对此有何评论?...
特朗普预警9月政府“停摆”,美... 一国总统公开预警自家联邦政府即将“停摆”,这种魔幻剧情又双叒叕要在华盛顿上演?当地时间7月22日,特...
视频丨2026年APEC数字和... 昨天(23日),2026年亚太经合组织数字和人工智能部长会议在四川成都举行。本届会议的主题为“数字和...
海南商发二期发射区土建完工,建... 7 月 24 日消息,海南商发今日宣布,海南商业航天发射场二期发射区建设项目土建工作完成,全面转入设...