使用java +paho mqtt编写模拟发布温度及订阅的过程

2024-06-22 11:28

本文主要是介绍使用java +paho mqtt编写模拟发布温度及订阅的过程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • 启动mqtt 服务
  •  创建项目,在项目中添加模块
  •  
  •  
  • 添加文件夹
    • 添加maven依赖
  •     <dependencies><dependency><groupId>org.eclipse.paho</groupId><artifactId>org.eclipse.paho.client.mqttv3</artifactId><version>1.2.0</version></dependency></dependencies>
    • 编写订阅程序  名字没起好 后面有时间再调整
  • import org.eclipse.paho.client.mqttv3.IMqttClient;
    import org.eclipse.paho.client.mqttv3.MqttMessage;import java.util.Random;
    import java.util.concurrent.Callable;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.TimeUnit;public class EngineTemperatureSensor implements Callable<Void> {// ... private members omittedIMqttClient client;public static final String TOPIC = "testTopic1/003";public EngineTemperatureSensor(IMqttClient client) {this.client = client;}@Overridepublic Void call() throws Exception {if ( !client.isConnected()) {return null;}CountDownLatch receivedSignal = new CountDownLatch(10);client.subscribe("testTopic1/003", (topic, msg) -> {byte[] payload = msg.getPayload();// ... payload handling omitted//print out the messageSystem.out.println("Received message: " + new String(payload));receivedSignal.countDown();});receivedSignal.await(1, TimeUnit.MINUTES);//print out the messageSystem.out.println("Published message:2222222222222 " );return null;}}
  • 订阅:

  • import org.eclipse.paho.client.mqttv3.IMqttClient;
    import org.eclipse.paho.client.mqttv3.MqttMessage;import java.util.Random;
    import java.util.concurrent.Callable;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.TimeUnit;public class EngineTemperatureSensor implements Callable<Void> {// ... private members omittedIMqttClient client;public static final String TOPIC = "testTopic1/003";public EngineTemperatureSensor(IMqttClient client) {this.client = client;}@Overridepublic Void call() throws Exception {if ( !client.isConnected()) {return null;}CountDownLatch receivedSignal = new CountDownLatch(10);client.subscribe("testTopic1/003", (topic, msg) -> {byte[] payload = msg.getPayload();// ... payload handling omitted//print out the messageSystem.out.println("Received message: " + new String(payload));receivedSignal.countDown();});receivedSignal.await(1, TimeUnit.MINUTES);//print out the messageSystem.out.println("Published message:2222222222222 " );return null;}}

import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;public class c5M {//main5public static void main(String[] args) {System.out.println("Hello World");String publisherId = UUID.randomUUID().toString();ExecutorService executor = Executors.newSingleThreadExecutor();try {IMqttClient subscriber = new MqttClient("tcp://127.0.0.1:1883", publisherId);MqttConnectOptions options = new MqttConnectOptions();options.setAutomaticReconnect(true);options.setCleanSession(true);options.setConnectionTimeout(10);subscriber.connect(options);// 调用EngineTemperatureSensorEngineTemperatureSensor sensor = new EngineTemperatureSensor(subscriber);executor.submit(sensor); // 提交任务,但不阻塞主线程// 这里可以添加代码来等待用户输入或者其他信号来安全地关闭程序// 例如,你可以使用System.in.read()来等待用户输入System.out.println("Press Enter to exit...");new Scanner(System.in).nextLine(); // 等待用户输入} catch (Exception e) {//print e message//print seperator lineSystem.out.println("))))))))))))))))))))))))");System.out.println(e.getMessage());throw new RuntimeException(e);} finally {// 确保最后关闭ExecutorService和MQTT客户端executor.shutdown(); // 提交的任务将不再被接受try {// 等待任务完成(可选,取决于你是否需要确保所有任务都完成)if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {executor.shutdownNow(); // 取消正在执行的任务}} catch (InterruptedException ie) {executor.shutdownNow(); // 当前线程被中断,需要关闭ExecutorServiceThread.currentThread().interrupt(); // 保留中断状态}// 关闭MQTT客户端(如果有必要的话)// 注意:这里可能需要额外的逻辑来处理MQTT客户端的关闭,具体取决于你的实现}}}

发布代码:

import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;public class EngineTemperatureSensor implements Callable<Void> {// ... private members omittedIMqttClient client;public static final String TOPIC = "testTopic1/003";public EngineTemperatureSensor(IMqttClient client) {this.client = client;}@Overridepublic Void call() throws Exception {if ( !client.isConnected()) {return null;}Random rnd = null;//double temp =  80 + rnd.nextDouble() * 20.0;double temp =  10 + 1.1 * 20.0;byte[] payload = String.format("T:%04.2f",temp).getBytes();MqttMessage msg2= new MqttMessage(payload);msg2.setQos(0);msg2.setRetained(true);client.publish(TOPIC,msg2);//print out the messageSystem.out.println("Published message: " + msg2);return null;}}

 

import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;public class mainc3 {// Main methodpublic static void main(String[] args) {System.out.println("Hello World");String publisherId = UUID.randomUUID().toString();ExecutorService executor = Executors.newSingleThreadExecutor();try {IMqttClient publisher = new MqttClient("tcp://127.0.0.1:1883", publisherId);MqttConnectOptions options = new MqttConnectOptions();options.setAutomaticReconnect(true);options.setCleanSession(true);options.setConnectionTimeout(10);publisher.connect(options);// 调用EngineTemperatureSensorEngineTemperatureSensor sensor = new EngineTemperatureSensor(publisher);executor.submit(sensor); // 提交任务,但不阻塞主线程// 这里可以添加代码来等待用户输入或者其他信号来安全地关闭程序// 例如,你可以使用System.in.read()来等待用户输入System.out.println("Press Enter to exit...");new Scanner(System.in).nextLine(); // 等待用户输入} catch (Exception e) {//print e message//print seperator lineSystem.out.println("))))))))))))))))))))))))");System.out.println(e.getMessage());throw new RuntimeException(e);} finally {// 确保最后关闭ExecutorService和MQTT客户端executor.shutdown(); // 提交的任务将不再被接受try {// 等待任务完成(可选,取决于你是否需要确保所有任务都完成)if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {executor.shutdownNow(); // 取消正在执行的任务}} catch (InterruptedException ie) {executor.shutdownNow(); // 当前线程被中断,需要关闭ExecutorServiceThread.currentThread().interrupt(); // 保留中断状态}// 关闭MQTT客户端(如果有必要的话)// 注意:这里可能需要额外的逻辑来处理MQTT客户端的关闭,具体取决于你的实现}}}

这篇关于使用java +paho mqtt编写模拟发布温度及订阅的过程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1084158

相关文章

Spring Security中用户名和密码的验证完整流程

《SpringSecurity中用户名和密码的验证完整流程》本文给大家介绍SpringSecurity中用户名和密码的验证完整流程,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 首先创建了一个UsernamePasswordAuthenticationTChina编程oken对象,这是S

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

MySQL中的InnoDB单表访问过程

《MySQL中的InnoDB单表访问过程》:本文主要介绍MySQL中的InnoDB单表访问过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、环境3、访问类型【1】const【2】ref【3】ref_or_null【4】range【5】index【6】

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

在Spring Boot中集成RabbitMQ的实战记录

《在SpringBoot中集成RabbitMQ的实战记录》本文介绍SpringBoot集成RabbitMQ的步骤,涵盖配置连接、消息发送与接收,并对比两种定义Exchange与队列的方式:手动声明(... 目录前言准备工作1. 安装 RabbitMQ2. 消息发送者(Producer)配置1. 创建 Spr