springboot整合mqtt

mqtt是一个轻量级的消息服务器

pom配置:

 <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mqtt</artifactId>
        </dependency>

配置文件配置:

# MQTT config
spring.mqtt.username=whl
spring.mqtt.password=123
spring.mqtt.url=tcp://192.168.100.10:1883
spring.mqtt.topics=demo_01
#spring.mqtt.client.id=Java_cline1245
spring.mqtt.completionTimeout=3000

mqtt配置:

package com.koala.console.configuration;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
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.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

/**
 * Created By Administrator
 * Date: 2018/9/18
 * Description:
 */
@Slf4j
//@Configuration
public class MQTTConfiguration {
    @Value("${spring.mqtt.topics}")
    private String topics;
    @Value("${spring.mqtt.url}")
    private String hostUrl;
    @Value("${spring.mqtt.username}")
    private String username;
    @Value("${spring.mqtt.password}")
    private String password;
    @Value("${spring.mqtt.client.id}")
    private String clientId;
    @Value("${spring.mqtt.completionTimeout}")
    private int completionTimeout;

    @Bean
    public MqttConnectOptions getMqttConnectOptions() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setKeepAliveInterval(2);
        mqttConnectOptions.setMaxInflight(100000000);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setConnectionTimeout(completionTimeout);
        return mqttConnectOptions;
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }

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

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


    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        //clientId使用随机数产生
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(RandomUtil.randomString(6), mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(topics);
        messageHandler.setDefaultRetained(false);
        return messageHandler;
    }


    @Bean
    public MessageProducer inbound() {
        String[] inboundTopics = topics.split(",");
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(RandomUtil.randomString(6), mqttClientFactory(), inboundTopics);
        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }


    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return new MessageHandler() {
        //消息消费
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                System.out.println(message.getPayload().toString());
                String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
                String type = topic.substring(topic.lastIndexOf("/")+1);
                if("livepage/wait".equalsIgnoreCase(topic)){
                    System.out.println("wait,fuckXX,"+message.getPayload().toString());
                }else if("demo_01".equalsIgnoreCase(topic)){
                    System.out.println("demo_01,fuckXX,"+message.getPayload().toString());
                }
            }
        };

        //return message -> log.info((String) message.getPayload());
    }
}

发送消息:

package com.koala.console.service;

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

@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttGateway {

    void sendToMqtt(String data,@Header(MqttHeaders.TOPIC) String topic);

}

 

发布了52 篇原创文章 · 获赞 39 · 访问量 23万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览