RabbitMQ整合SpringBoot做一些简单的消息发送。
虽然只是使用了简单的fanout模式推送的消息,不过其他模式也一样,无非就是匹配路由键的规则。
RabbitMQ基本概念和使用可以看看这里:https://blog.csdn.net/xianyun1992/article/details/107699839
创建SpringBoot项目:
1、首先创建一个普通的SpringBoot项目,添加RabbitMQ的maven依赖:
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2、创建配置类,实现自动注入:
@Configuration
public class FanoutConfig {
@Bean
public Queue MessageA() {
return new Queue("fanout.a");
}
@Bean
FanoutExchange fanoutExchange() {
return new FanoutExchange("fanoutExchange");
}
@Bean
Binding bindingExchangeA(Queue MessageA, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(MessageA).to(fanoutExchange);
}
}
3、创建消费者:
@Component
@RabbitListener(queues = "fanout.a")
public class FanoutCustomer {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@RabbitHandler
public void process(String message) {
log.info("接收消息:{}", message);
}
}
4、创建生产者:
@Component
public class FanoutSend {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send(String msg) {
this.rabbitTemplate.convertAndSend("fanoutExchange","", msg);
}
}
5、配置yml文件:
server:
port: 8080
spring:
application:
name: spring-boot-rabbitmq
rabbitmq:
host: 106.13.56.12
port: 5672
username: admin
password: admin
6、测试消息发送:
@SpringBootTest
class RabbitmqSpringbootApplicationTests {
@Autowired
FanoutSend fanoutSend;
@Test
public void fanoutSend() {
fanoutSend.send("测试fanout发送。。。");
}
}
7、结果: