@RabbitListener(queues = “MyQueue”) does not work in Spring project?

时间秒杀一切 提交于 2020-06-16 04:19:18

问题


I am trying to implement rabbitmq in my Spring application, not spring boot. So I added this configuration


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");
    }


}

Then from my service class I have used:-

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);
    }

The convertAndSend seems working as expected, but When the message is pushed into the queue, the ListenToMyQueue should be auto executed as new element is inserted into the queue, right? Why this is not working?


回答1:


For future refference, after many days of try, finally this listener configuration is working as expected. enter link description here



来源:https://stackoverflow.com/questions/62039093/rabbitlistenerqueues-myqueue-does-not-work-in-spring-project

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