使用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

相关文章

如何使用 Python 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

SpringBoot请求参数接收控制指南分享

《SpringBoot请求参数接收控制指南分享》:本文主要介绍SpringBoot请求参数接收控制指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring Boot 请求参数接收控制指南1. 概述2. 有注解时参数接收方式对比3. 无注解时接收参数默认位置

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring

Spring Boot 整合 SSE的高级实践(Server-Sent Events)

《SpringBoot整合SSE的高级实践(Server-SentEvents)》SSE(Server-SentEvents)是一种基于HTTP协议的单向通信机制,允许服务器向浏览器持续发送实... 目录1、简述2、Spring Boot 中的SSE实现2.1 添加依赖2.2 实现后端接口2.3 配置超时时

解决Maven项目idea找不到本地仓库jar包问题以及使用mvn install:install-file

《解决Maven项目idea找不到本地仓库jar包问题以及使用mvninstall:install-file》:本文主要介绍解决Maven项目idea找不到本地仓库jar包问题以及使用mvnin... 目录Maven项目idea找不到本地仓库jar包以及使用mvn install:install-file基

Spring Boot读取配置文件的五种方式小结

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进... 目录1. 配置文件位置与加载顺序2. 读取配置文件的方式汇总方式一:使用 @Value 注解读取配置方式二

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Java中的@SneakyThrows注解用法详解

《Java中的@SneakyThrows注解用法详解》:本文主要介绍Java中的@SneakyThrows注解用法的相关资料,Lombok的@SneakyThrows注解简化了Java方法中的异常... 目录前言一、@SneakyThrows 简介1.1 什么是 Lombok?二、@SneakyThrows

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自