使用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 Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Java中的工具类命名方法

《Java中的工具类命名方法》:本文主要介绍Java中的工具类究竟如何命名,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java中的工具类究竟如何命名?先来几个例子几种命名方式的比较到底如何命名 ?总结Java中的工具类究竟如何命名?先来几个例子JD

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

SpringBoot整合OpenFeign的完整指南

《SpringBoot整合OpenFeign的完整指南》OpenFeign是由Netflix开发的一个声明式Web服务客户端,它使得编写HTTP客户端变得更加简单,本文为大家介绍了SpringBoot... 目录什么是OpenFeign环境准备创建 Spring Boot 项目添加依赖启用 OpenFeig

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删