Rabbitmq 使用@queuebinding和@rabbitlistener声明并绑定队列不工作?
我试图使用annotation和rabbitlistener制作一个spring amqp示例,但在使用queuebinding自动声明队列时,它没有成功。 有什么建议吗??非常感谢 以下是消费者代码:Rabbitmq 使用@queuebinding和@rabbitlistener声明并绑定队列不工作?,rabbitmq,spring-amqp,Rabbitmq,Spring Amqp,我试图使用annotation和rabbitlistener制作一个spring amqp示例,但在使用queuebinding自动声明队列时,它没有成功。 有什么建议吗??非常感谢 以下是消费者代码: @Component public class Consumer { @RabbitListener(bindings = @QueueBinding( value = @Queue(value = "queue1", durable = "true") ,
@Component
public class Consumer {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue1", durable = "true") ,
exchange = @Exchange(value = "test"),
key = "hello1") )
public void handleHello1(String text) {
System.out.println("Received: " + text);
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue2", durable = "true") ,
exchange = @Exchange(value = "test") ,
key = "hello2") )
public void handleHello2(String text) {
System.out.println("Received: " + text);
}
}
配置代码:
@Configuration
@EnableRabbit
public class Config {
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
System.out.println("create rabbitListenerContainerFactory");
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory());
factory.setConcurrentConsumers(3);
factory.setMaxConcurrentConsumers(10);
return factory;
}
@Bean
public AmqpAdmin amqpAdmin() {
AmqpAdmin admin = new RabbitAdmin(connectionFactory());
System.out.println("create amqpAdmin");
return admin;
}
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory());
return template;
}
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory("127.0.0.1");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
return connectionFactory;
}
@Bean
public ScheduledProducer scheduledProducer() {
return new ScheduledProducer();
}
@Bean
public BeanPostProcessor postProcessor() {
return new ScheduledAnnotationBeanPostProcessor();
}
static class ScheduledProducer {
@Autowired
private volatile RabbitTemplate rabbitTemplate;
private final AtomicInteger counter = new AtomicInteger();
@Scheduled(fixedRate = 3000)
public void sendMessage() {
String str = "hello" +(counter.get() % 2);
System.out.println("routingkey:" + str);
rabbitTemplate.convertAndSend("test", str, "Hello World " + counter.incrementAndGet());
}
}
}
生产代码:
public class Producer {
public static void main(String[] args) throws Exception {
new AnnotationConfigApplicationContext(Config.class);
}
}
您需要将
消费者
添加到配置
类中
@Bean
public Consumer consumer() {
return new Consumer();
}
(或在Config
上启用组件扫描)
绑定中的路由键也错误-您正在发送到hello0
和hello1
@ComponentScan(basePackages="foo")