本文参考spring官方给的文档,地址:

https://docs.spring.io/spring-integration/reference/html/mqtt.html

采用Gateway绑定的方式,网上也有采用paho Mqtt client库实现的,但是比较麻烦。

1. 引入相关依赖

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

2.  配置MQTT服务器基本信息,在springBoot配置文件application.yml中配置,添加如下:

#MQTT配置信息
#MQTT-用户名
spring.mqtt.username=admin
#MQTT-密码
spring.mqtt.password=password
#MQTT-服务器连接地址,如果有多个,用逗号隔开,如:tcp://127.0.0.1:61613,tcp://192.168.2.133:61613
spring.mqtt.url=tcp://127.0.0.1:61613
#MQTT-连接服务器默认客户端ID
spring.mqtt.client.id=mqttId
#MQTT-默认的消息推送主题,实际可在调用接口时指定
spring.mqtt.default.topic=topic

3. 配置MQTT消息推送配置类,

**
 * 〈一句话功能简述〉<br> 
 * 〈MQTT发送消息配置〉
 *
 * @author AnswerChang
 * @create 2018/6/4
 * @since 1.0.0
 */
@Configuration
@IntegrationComponentScan
public class MqttSenderConfig {

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

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

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

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

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

    @Bean
    public MqttConnectOptions getMqttConnectOptions(){
        MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setKeepAliveInterval(2);
        return mqttConnectOptions;
    }
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler =  new MqttPahoMessageHandler(clientId, mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(defaultTopic);
        return messageHandler;
    }
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }
}

4. 配置MqttGateway消息推送接口类,在sendToMqtt(String data,@Header(MqttHeaders.TOPIC)String topic)接口中,data为发送的消息内容,topic为主题。指定topic,则我们的接口可以根据需要,向不同的主题发送消息,方便灵活应用。如果不指定,则使用默认配置的主题。

@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttGateway {
    void sendToMqtt(String data,@Header(MqttHeaders.TOPIC) String topic);
}

5. 最后,写个接口类测试下功能,用Postman调用sendMqtt.do接口,往hello主题发送消息,用MQTTLens订阅hello主题,从下面截图,可以看出可以正常往MQTT服务发送消息了,而且可以订阅到。

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private MqttGateway mqttGateway;

    @RequestMapping("/sendMqtt.do")
    public String sendMqtt(String  sendData){
        mqttGateway.sendToMqtt(sendData,"hello");
        return "OK";
    }
}

最后使用Google浏览器 MQTTLens插件进行测试

转自:

https://blog.csdn.net/qq_41018959/article/details/80592444

https://blog.csdn.net/qq_41018959/article/details/80564347

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐