目录
2. 在 application.yml 中配置rabbitmq的 连接信息:
这是Work Queues 的竞争模式,如果想要公平模式的效果,只需要将消费者中的 channel.basicQos(1)注释掉;
1.先加入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 在 application.yml 中配置rabbitmq的 连接信息:
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
listener:
simple:
acknowledge-mode: manual
prefetch: 1
3.队列配置,启动时创建队列
@Configuration
public class RabbitMqConfig {
@Bean
public Queue createQueue(){
return new Queue("hello-queue");
}
}
4.创建生产者
@Component
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate;
public void sendTest(String msg){
this.amqpTemplate.convertAndSend("hello-queue",msg);
}
}
5.创建两个消费者
第一个
@Component
public class Receiver {
@SneakyThrows
@RabbitListener(queues = "hello-queue")
public void process(String msg,Channel channel,Message message){
TimeUnit.SECONDS.sleep(1);
channel.basicQos(1);
System.out.println("receiver: "+msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
}
第二个
@Component
public class Receiver2 {
@SneakyThrows
@RabbitListener(queues = "hello-queue")
public void process(String msg, Channel channel, Message message){
channel.basicQos(1);
TimeUnit.SECONDS.sleep(2);
System.out.println("receiver2: "+msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
}
6.测试类中测试
@SpringBootTest
class Rabbitmt1ApplicationTests {
@Autowired
private Sender sender;
@Test
void contextLoads() {
sender.send("rabbit-mq-test");
}
}