持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第6天,点击查看活动详情
上文讲到如何用Java操作RabbitMQ这次我们用目前最常见的SpringBoot来操作RabbitMQ。
1 通过SpringBoot声明信息
1.1 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
1.2 配置RabbitMQ信息
需要让项目知道RabbitMQ在哪,需要配置地址,端口,用户名,密码,virtual-host等基本信息。
spring:
rabbitmq:
host: 192.168.11.32
port: 5672
username: guest
password: guest
virtual-host: /
1.3 声明交换机&队列
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE = "boot-exchange";
public static final String QUEUE = "boot-queue";
public static final String ROUTING_KEY = "*.black.*";
@Bean
public Exchange bootExchange(){
// channel.DeclareExchange
return ExchangeBuilder.topicExchange(EXCHANGE).build();
}
@Bean
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE).build();
}
@Bean
public Binding bootBinding(Exchange bootExchange,Queue bootQueue){
return BindingBuilder.bind(bootQueue).to(bootExchange).with(ROUTING_KEY).noargs();
}
}
2 生产者操作
@SpringBootTest
public class PublisherTest {
@Autowired
public RabbitTemplate rabbitTemplate;
@Test
public void publish(){
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE,"big.black.dog","message");
System.out.println("消息发送成功");
}
@Test
public void publishWithProps(){
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE, "big.black.dog", "messageWithProps", new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
message.getMessageProperties().setCorrelationId("123");
return message;
}
});
System.out.println("消息发送成功");
}
}
3 消费者操作
@Component
public class ConsumeListener {
@RabbitListener(queues = RabbitMQConfig.QUEUE)
public void consume(String msg, Channel channel, Message message) throws IOException {
System.out.println("队列的消息为:" + msg);
String correlationId = message.getMessageProperties().getCorrelationId();
System.out.println("唯一标识为:" + correlationId);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}
}
public void consume(String msg, Channel channel, Message message)
msg是接收到的消息,会自动进行序列化与反序列化,可以是User等实体类channel想要加channel必须在配置文件内加
spring:
rabbitmq:
listener:
simple:
scknowledge-mode:manual #开启手动ACK
prefetch: 10 每次取消息的数量
message会包含消息的所有信息,包括携带的属性和消息内容,和生产者发送消息的message是一样的。
@RabbitListener(queues = RabbitMQConfig.QUEUE)
这个注解标识这个方法会监听队列RabbitMQConfig.QUEUE,只要队列中有消息,就进行消费。
这样就完成了SpringBoot通过RabbitMQ发送消息和消费消息。