springboot结合mqtt服务器构建消息生产与消费示例

部署运行你感兴趣的模型镜像

    mqtt服务,是一个消息中间件,目前在物联网领域使用非常广泛。

    mqtt服务器的搭建,也有很多方式,最直接的就是使用docker启动emqx镜像。

docker run -d --name emqx -p 18083:18083 -p 1883:1883 emqx

    通过url访问webui。http://192.168.56.100:18083 用户名密码:admin/public

mqtt与springboot结合 

    引入maven依赖

<parent>
  	<groupId>org.springframework.boot</groupId>
  	<artifactId>spring-boot-starter-parent</artifactId>
  	<version>2.4.3</version>
  </parent>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-integration</artifactId>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework.integration</groupId>
    	<artifactId>spring-integration-stream</artifactId>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework.integration</groupId>
    	<artifactId>spring-integration-mqtt</artifactId>
    </dependency>
    
    <dependency>
    	<groupId>org.eclipse.paho</groupId>
    	<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    	<version>1.2.5</version>
    </dependency>
    
  </dependencies>

    设置配置文件application.yml

mqtt:
  serverURIs: tcp://192.168.226.100:1883
  username: admin
  password: public
  client:
    id: ${random.value}
  topic: topic_default

    设置配置类 MqttConfig.java

package com.xxx.mqttapp.config;
import java.util.Objects;
import javax.annotation.PostConstruct;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
@IntegrationComponentScan
@Configuration
public class MqttConfig {
	public static final Logger log = LoggerFactory.getLogger(MqttConfig.class);
	public static final String OUTBOUND_CHANNEL = "mqttOutboundChannel";

    public static final String INPUT_CHANNEL = "mqttInputChannel";

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.serverURIs}")
    private String hostUrl;

    @Value("${mqtt.client.id}")
    private String clientId;

    @Value("${mqtt.topic}")
    private String defaultTopic;

    @PostConstruct
    public void init() {
        log.debug("username:{} password:{} hostUrl:{} clientId :{} ",
                this.username, this.password, this.hostUrl, this.clientId, this.defaultTopic);
    }

    @Bean
    public MqttPahoClientFactory clientFactory() {

        final MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{hostUrl});
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        final DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(options);
        return factory;
    }

    @Bean(value = OUTBOUND_CHANNEL)
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = OUTBOUND_CHANNEL)
    public MessageHandler mqttOutbound() {

        final MqttPahoMessageHandler handler = new MqttPahoMessageHandler(clientId, clientFactory());
        handler.setDefaultQos(1);
        handler.setDefaultRetained(false);
        handler.setDefaultTopic(defaultTopic);
        handler.setAsync(false);
        handler.setAsyncEvents(false);
        return handler;
    }

    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageProducer inbound() {
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(
                        clientId + "_inbound", clientFactory(), defaultTopic);
        adapter.setCompletionTimeout(3000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    @Bean
    @ServiceActivator(inputChannel = INPUT_CHANNEL)
    public MessageHandler handler() {
        return message -> {
            String topic = Objects.requireNonNull(message.getHeaders().get("mqtt_receivedTopic")).toString();
            log.info("topic: {},payload : {}", topic,message.getPayload().toString());
        };
    }
}

    添加发送接口MqttGateway.java

package com.xxx.mqttapp.service;

import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.handler.annotation.Header;

import com.xxx.mqttapp.config.MqttConfig;

@MessagingGateway(defaultRequestChannel = MqttConfig.OUTBOUND_CHANNEL)
public interface MqttGateway {
	public void sendToMqtt(@Header(MqttHeaders.TOPIC)String topic,String payload);
}

    定义发送控制器

package com.xxx.mqttapp.web;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xxx.mqttapp.service.MqttGateway;
@RequestMapping("/test")
@RestController
public class TestController {
	@Autowired
	private MqttGateway mqttGateway;
	
	@PostMapping("/sendMessage")
	public Map<String, Object> sendMessage(String topic,String payload){
		Map<String, Object> result = new HashMap<String, Object>();
		mqttGateway.sendToMqtt(topic, payload);
		result.put("topic", topic);
		result.put("payload", payload);
		return result;
	}
	
}

    springboot启动类

package com.xxx.mqttapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
    public static void main( String[] args ){
    	SpringApplication.run(App.class, args);
    }
}

    启动springboot应用,测试:

    消息发送成功,控制台打印消息如下:

    这个测试,不是直接发送消息到mqtt服务器,而是借助web接口,发送http请求,后台接收,然后调用生产者发送方法。

    消费者直接配置了一个MqttPahoMessageDrivenChannelAdapter,并订阅defaultTopic主题,他需要设置一个channel和一个handler。所以,生产者一发送消息过来,消费者立马就消费掉了。

您可能感兴趣的与本文相关的镜像

Llama Factory

Llama Factory

模型微调
LLama-Factory

LLaMA Factory 是一个简单易用且高效的大型语言模型(Large Language Model)训练与微调平台。通过 LLaMA Factory,可以在无需编写任何代码的前提下,在本地完成上百种预训练模型的微调

### 使用 Spring Boot 连接到 MQTT 服务器 为了使应用程序能够通过 MQTT 协议发送和接收消息,可以利用 `Eclipse Paho` 客户端库来实现这一功能。当在 Spring Boot 应用程序中集成 MQTT 支持时,通常会引入依赖项以便简化配置过程。 #### 添加 Maven 或 Gradle 依赖 对于基于 Maven 的项目,在 pom.xml 文件里加入如下依赖: ```xml <dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>{latest-version}</version> </dependency> <!-- 如果想要使用 spring-integration-mqtt --> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> <version>{compatible-spring-boot-version}</version> </dependency> ``` 而对于采用 Gradle 构建工具,则应在 build.gradle 中添加相应的依赖声明: ```groovy implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:{latest-version}' // 可选:如果要使用 spring integration mqtt支持 implementation 'org.springframework.integration:spring-integration-mqtt:{compatible-spring-boot-version}' ``` 以上代码片段展示了如何向构建文件中添加必要的依赖关系以启用对 MQTT 的访问[^1]。 #### 配置 MQTT 属性 接着定义一些用于连接到特定 MQTT 经纪人的属性设置,这些可以在 application.properties 或者 application.yml 文件里面完成: ```properties mqtt.broker.url=tcp://localhost:1883 mqtt.default.topic=test/topic mqtt.username=yourUsername mqtt.password=yourPassword ``` 或者 YAML 格式的配置方式为: ```yaml mqtt: broker: url: tcp://localhost:1883 defaultTopic: test/topic username: yourUsername password: yourPassword ``` 上述配置指定了目标 MQTT Broker 地址以及其他认证所需的信息。 #### 编写 Java 类处理订阅/发布操作 创建一个新的类用来管理 MQTT Server 的交互逻辑,这里提供了一个简单的例子说明怎样监听来自指定主题的消息以及广播自定义负载给其他客户端: ```java import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; public class MqttExample { private static final String BROKER_URL = "tcp://localhost:1883"; private static final String TOPIC_NAME = "test/topic"; public void start() throws MqttException { try (MqttClient client = new MqttClient(BROKER_URL, MqttClient.generateClientId())) { client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) {} @Override public void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println("Received Message from [" + topic + "] : " + new String(message.getPayload())); } @Override public void deliveryComplete(IMqttDeliveryToken token) {} }); client.connect(); client.subscribe(TOPIC_NAME); // 发布一条测试消息至该主题下 MqttMessage msg = new MqttMessage("Hello World".getBytes()); client.publish(TOPIC_NAME,msg); Thread.sleep(5000); // 等待一段时间再断开连接 client.disconnect(); } } } ``` 这段示例演示了基本的 MQTT 订阅者行为模式——建立连接、注册回调函数响应接收到的数据包事件并最终关闭通信链路的过程。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值