1

我正在尝试在我的Spring应用程序中实现 rabbitmq,而不是 spring boot。所以我添加了这个配置


import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfiguration {

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory =
                new CachingConnectionFactory("localhost");
        return connectionFactory;
    }

    @Bean
    public AmqpAdmin amqpAdmin() {
        return new RabbitAdmin(connectionFactory());
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        return new RabbitTemplate(connectionFactory());
    }

    @Bean
    public Queue myQueue() {
        return new Queue("MyQueue");
    }


}

然后从我使用过的服务类中:-

public void sendViaTemplate(String msg){
        ApplicationContext context =
                new AnnotationConfigApplicationContext(RabbitConfiguration.class);


        RabbitTemplate template = context.getBean(RabbitTemplate.class);

        template.convertAndSend(QUEUE_NAME,"Hello from template "+msg);
    }

    @RabbitListener(queues = "MyQueue")
    public void ListenToMyQueue( String in){
        System.out.println("New Msg arrived"+in);
    }

convertAndSend 似乎按预期工作,但是当消息被推入队列时,ListenToMyQueue 应该在新元素插入队列时自动执行,对吧?为什么这不起作用?

4

1 回答 1

0

为了将来参考,经过多天的尝试,这个监听器配置终于按预期工作了。在此处输入链接描述

于 2020-05-27T15:18:56.703 回答