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

后端 未结 1 1331
我寻月下人不归
我寻月下人不归 2021-01-27 17:53

So I\'ve gotten MQTT -> MQTT and AMQP -> AMQP to work; the translation of MQTT -> AMQP doesn\'t seem to be working somewhere though. Here\'s my test, it passes if my \"listener\

相关标签:
1条回答
  • 2021-01-27 18:49

    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"));
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题