问题
最近项目中需要在Spring中使用RabbitMQ进行消息的推送和监听。
概念
在RabbitMQ中,主要有Exchange,Routing Key,Queue,这3个概念。
消息生产者将消息给Exchange,Exchange根据Routing Key与Queue的路由绑定规则来,判定哪些消息去哪些Queue。消息消费者监听Queue就阔以了。
步骤
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
properties
单机版配置如下:
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
托管版配置如下:
spring:
rabbitmq:
virtual-host: feature1
addresses: xxx.com
username: guest
password: guest
Java
import org.springframework.amqp.support.converter.MessageConverter;
@SpringBootApplication
public class Application {
...
@Bean
MessageConverter createMessageConverter() {
return new Jackson2JsonMessageConverter();
}
}
推送消息
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
@Slf4j
@Service
public class MessagingServiceImpl implements MessagingService {
...
@Value("${exchange.xxx.xxx:xxx.exchange}")
private String exchange;
@Value("${routing.key.xxx.xxx:xxx.routing.key}")
private String routingKey;
@Resource private RabbitTemplate rabbitTemplate;
@Override
public void sendMessage(String message) {
rabbitTemplate.convertAndSend(exchange, routingKey, message);
}
...
}
推送消息的时候,主要使用RabbitTemplate
,只要知道Exchange,Routing Key就可以进行消息推送了,并不需要了解是推送到那个队列。
监听消息
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
@Slf4j
@Service
public class MessagingServiceImpl implements MessagingService {
private final String QUEUE = "xxxx.queue";
....
@Override
@RabbitListener(queues = QUEUE)
public void receiveQueue(String message) {
log.info("queue {} received registration message: {}", QUEUE, message);
....
}
}
监听消息的时候,只需要使用@RabbitListener(queues = xxx)
进行消息队列监听就阔以了,并不需要了解Exchange,Routing Key。
总结
Spring amqp中使用RabbitMQ的消息发送和监听,主要就是使用RabbitTemplate
和@RabbitListener
注解。