搭建MQTT服务,使用ubuntu搭建EMQX并用Springboot进行连接测试
在Ubuntu上搭建EMQX并用Spring Boot进行连接测试的步骤如下:
- 安装EMQX:
wget https://www.emqx.io/downloads/emqx-ubuntu1404-v4.0.1.zip
unzip emqx-ubuntu1404-v4.0.1.zip
cd emqx
./bin/emqx console
- 在Spring Boot项目中添加MQTT依赖:
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
<version>5.5.1</version>
</dependency>
- 配置application.properties或application.yml文件:
spring.mqtt.username=test
spring.mqtt.password=public
spring.mqtt.host-url=tcp://localhost:1883
spring.mqtt.client.server-uris=tcp://localhost:1883
spring.mqtt.client.client-id=client1
- 创建配置类MqttConfig.java:
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.messaging.channel.DirectChannel;
@Configuration
public class MqttConfig {
@Bean
public MqttConnectOptions getMqttConnectOptions() {
MqttConnectOptions options = new MqttConnectOptions();
options.setServerURIs(new String[]{"tcp://localhost:1883"});
options.setUserName("test");
options.setPassword("public".toCharArray());
options.setCleanSession(true);
return options;
}
@Bean
public MqttPahoClientFactory mqttClientFactory() {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
factory.setConnectionOptions(getMqttConnectOptions());
return factory;
}
@Bean
public DirectChannel mqttInputChannel() {
return new DirectChannel();
}
@Bean
public MqttPahoMessageDrivenChannelAdapter mqttPahoMessageDrivenChannelAdapter(MqttPahoClientFactory mqttPahoClientFactory, DirectChannel mqttInputChannel) {
MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("client1", mqttPahoClientFactory, "testTopic");
adapter.setCompletionTimeout(5000);
adapter.setOutputChannel(mqttInputChannel);
return adapter;
}
}
- 创建监听器MqttListener.java:
import org.spring
评论已关闭