How can I transmit via MQTT and Receive on AMQP with RabbitMQ and Spring-AMQP

牧云@^-^@ 提交于 2019-12-02 07:41:23

The MQTT plugin publishes to the amq.topic with the mqtt topic name as the routing key.

On the consumer side, it binds an auto-delete queue to that exchange, with the routing key; in the following example, the queue is named mqtt-subscription-mqttConsumerqos1.

In order to receive MQTT messages over AMQP, you need to bind your own queue to the exchange. Here is an example:

@SpringBootApplication
public class So54995261Application {

    public static void main(String[] args) {
        SpringApplication.run(So54995261Application.class, args);
    }

    @Bean
    @ServiceActivator(inputChannel = "toMQTT")
    public MqttPahoMessageHandler sendIt(MqttPahoClientFactory clientFactory) {
        MqttPahoMessageHandler handler = new MqttPahoMessageHandler("clientId", clientFactory);
        handler.setAsync(true);
        handler.setDefaultTopic("so54995261");
        return handler;
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[] { "tcp://localhost:1883" });
        options.setUserName("guest");
        options.setPassword("guest".toCharArray());
        factory.setConnectionOptions(options);
        return factory;
    }

    @Bean
    public MessageProducerSupport mqttInbound() {
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("mqttConsumer",
                mqttClientFactory(), "so54995261");
        adapter.setCompletionTimeout(5000);
        return adapter;
    }

    @Bean
    public IntegrationFlow flow() {
        return IntegrationFlows.from(mqttInbound())
                .handle(System.out::println)
                .get();
    }

    @RabbitListener(queues = "so54995261")
    public void listen(byte[] in) {
        System.out.println(new String(in));
    }

    @Bean
    public Queue queue() {
        return new Queue("so54995261");
    }

    @Bean
    public Binding binding() {
        return new Binding("so54995261", DestinationType.QUEUE, "amq.topic", "so54995261", null);
    }

    @Bean
    public ApplicationRunner runner(MessageChannel toMQTT) {
        return args -> toMQTT.send(new GenericMessage<>("foo"));
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!