Spring Boot整合RabbitMQ
Spring有三种配置方式
- 基于XML
- 基于JavaConfig
- 基于注解
当然现在已经很少使用XML来做配置了,只介绍一下用JavaConfig和注解的配置方式
RabbitMQ整合Spring Boot,我们只需要增加对应的starter即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
基于注解
在application.yaml的配置如下
spring:
rabbitmq:
host: myhost
port: 5672
username: guest
password: guest
virtual-host: /
log:
exchange: log.exchange
info:
queue: info.log.queue
binding-key: info.log.key
error:
queue: error.log.queue
binding-key: error.log.key
all:
queue: all.log.queue
binding-key: '*.log.key'
消费者代码如下
@Slf4j
@Component
public class LogReceiverListener {
/**
* 接收info级别的日志
*/
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(value = "${log.info.queue}", durable = "true"),
exchange = @Exchange(value = "${log.exchange}", type = ExchangeTypes.TOPIC),
key = "${log.info.binding-key}"
)
)
public void infoLog(Message message) {
String msg = new String(message.getBody());
log.info("infoLogQueue 收到的消息为: {}", msg);
}
/**
* 接收所有的日志
*/
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(value = "${log.all.queue}", durable = "true"),
exchange = @Exchange(value = "${log.exchange}", type = ExchangeTypes.TOPIC),
key = "${log.all.binding-key}"
)
)
public void allLog(Message message) {
String msg = new String(message.getBody());
log.info("allLogQueue 收到的消息为: {}", msg);
}
}
生产者如下
@RunWith(SpringRunner.class)
@SpringBootTest
public class MsgProducerTest {
@Autowired
private AmqpTemplate amqpTemplate;
@Value("${log.exchange}")
private String exchange;
@Value("${log.info.binding-key}")
private String routingKey;
@SneakyThrows
@Test
public void sendMsg() {
for (i