0%

Springboot集成RabbitMQ


一、什么是RabbitMQ

RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件)。RabbitMQ服务器是用Erlang语言编写的,而集群和故障转移是构建在开放电信平台框架上的。所有主要的编程语言均有与代理接口通讯的客户端库。


二、添加依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

三、添加配置文件创建消息队列

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class MessageConfig {

public final static String EMAIL_QUEUE_NAME = "emailQueue";

@Bean
public Queue emailQueue() {
//队列名,是否持久化
return new Queue(EMAIL_QUEUE_NAME, true);
}

}

四、创建消息队列发送者

下面的生产者与消费者是我用来一步发送邮件的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Service
public class MessageSender {

public Logger logger = LoggerFactory.getLogger(getClass());

@Autowired
AmqpTemplate amqpTemplate;

public void sendTopicEmail(Email emailEntity) {
String email = ConvertUtil.beanToString(emailEntity);
logger.debug(" [RabbitMQ] MessageSender.sendTopicEmail 向 {} 队列发送邮件消息 -> : {}", EMAIL_QUEUE_NAME, emailEntity);
amqpTemplate.convertAndSend(EMAIL_QUEUE_NAME, email);
}

}


五、创建消队列息监听者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Service
public class MessageReceiver {

public Logger logger = LoggerFactory.getLogger(getClass());

@Autowired
EmailService emailService;

@RabbitListener(queues = MessageConfig.EMAIL_QUEUE_NAME)
public void receiveEmail1(String message) {
Email email = ConvertUtil.stringToBean(message, Email.class);
logger.debug(" [RabbitMQ] MessageReceiver.receiveEmail 获取 {} 队列的邮件消息 -> : {}", MessageConfig.EMAIL_QUEUE_NAME, email);
emailService.sendEmail(email);
}

}