前言:
之前介绍了rabbitMq是用来干什么的,以及存在的意义是什么,现在与springBoot集成,用一个例子来体会一下。
Spring-amqp是对AMQP协议的抽象实现,而spring-rabbit 是对协议的具体实现,也是目前的唯一实现。底层使用的就是RabbitMQ。
1、启动类:
@SpringBootApplication
public class RabbitmqDemoApplication {
public static void main(String[] args) {
SpringApplication.run(RabbitmqDemoApplication.class, args);
}
}
2、添加AMQP启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
3、yml配置文件中添加RabbitMQ地址
spring:
rabbitmq:
host: 自己的服务器地址
username: leyou
password: 1234
virtual-host: /v_leyou
4、生产者
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RabbitmqDemoApplication.class)
public class SendMsg {
@Autowired
private AmqpTemplate amqpTemplate;
@Test
public void testSend() throws InterruptedException {
String msg = "hello, rabbitMq";
this.amqpTemplate.convertAndSend("SPRING.TEST.EXCHANGE","a.b", msg);
// 等待10秒后再结束
Thread.sleep(10000);
}
}
5、消费者(监听)
@Component
public class Listener {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "SPRING.TEST.QUEUE",durable="true"),
exchange = @Exchange(
value = "SPRING.TEST.EXCHANGE",
ignoreDeclarationExceptions = "true",
type = ExchangeTypes.TOPIC
),
key = {"#.#"}))
public void listen(String msg){
System.out.println("接收到消息:" + msg);
}
}
- @RabbitListener:方法上的注解,声明这个方法是一个消费者方法,需要指定下面的属性:
- bindings:指定绑定关系,可以有多个。值是@QueueBinding的数组。@QueueBinding包含下面属性:
- value:这个消费者关联的队列。值是@Queue,代表一个队列 durable = "true"持久化
- exchange:队列所绑定的交换机,值是@Exchange类型
- key:队列和交换机绑定的RoutingKey,#.#表示这个路由规则
- bindings:指定绑定关系,可以有多个。值是@QueueBinding的数组。@QueueBinding包含下面属性:
ignoreDeclarationExceptions = “true” 解决的是下游问题,例如:由于没有声明另一个队列(在错误队列之后定义的),侦听器容器无法初始化。此时将值设置为true,解决了问题
类似listen这样的方法在一个类中可以写多个,就代表多个消费者。
此时我们启动这个服务,看下我们的rabbitMq
控制台: