步骤一
pom.xml 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>com.alibaba</groupId>-->
<!--<artifactId>fastjson</artifactId>-->
<!--<version>1.2.37</version>-->
<!--</dependency>-->
步骤二
启动类上,打上注解
@EnableRabbit
步骤三
application.properties 配置
spring.application.name=springboot-rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
步骤四
配置类
//生产者配置
@Configuration
public class RabbitmqConfig {
//Topic交换器
@Bean
public TopicExchange exchange() {
return new TopicExchange("exchange");
}
//队列
@Bean
public Queue queue() {
return new Queue("queue");
}
//如果前面定义了多个Queue或TopicExchange 可以用@Qualifier标明入参注入哪一个
@Bean
Binding bindingExchangeMessage(Queue queue,
TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).
with("routingKey");
}
}
步骤五
生产者发消息
@Component
public class RabbitmqSender {
@Autowired
private AmqpTemplate amqpTemplate;
//自定义一个pojo
public void sendMessage(String exchange,String roukekey,Message content) {
try {
amqpTemplate.convertAndSend(exchange, roukekey,
//fastjson
JSONObject.toJSONString(content));
}catch (Exception e) {
}
}
}
消费者消费
@Component
public class MessageListener {
@RabbitListener(queues = "queue")
public void process(String strmsg) {
final Message message = JSONObject.parseObject(strmsg,Message.class);
}
}
或者
@Component
@RabbitListener(queues = "queue")
public class MessageListener {
@RabbitHandler
public void process(String strmsg) {
final Message message = JSONObject.parseObject(strmsg,Message.class);
}
}

本文详细介绍了如何使用Spring Boot框架整合RabbitMQ,包括引入依赖、配置启动注解、设置application.properties、创建配置类、实现生产者发送消息及消费者接收消息的全过程。
50万+

被折叠的 条评论
为什么被折叠?



