RabbitMQ基础入门(五)Spring AMQP
Spring-amqp是对AMQP协议的抽象实现,而spring-rabbit 是对协议的具体实现,也是目前的唯一实现。底层使用的就是RabbitMQ。
1. 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 添加配置
spring:
rabbitmq:
host: 192.168.142.128
username: youshop
password: youshop
port: 5672
virtual-host: youshop
template:
exchange: youshop.item.exchange # 缺省的交换机名称,此处配置后,发送消息如果不指定交换机就会使用这个
publisher-confirms: true # 生产者确认机制,确保消息会正确发送,如果发送失败会有错误回执,从而触发重试
- template:有关AmqpTemplate的配置
- exchange:缺省的交换机名称,此处配置后,发送消息如果不指定交换机就会使用这个
- publisher-confirms:生产者确认机制,确保消息会正确发送,如果发送失败会有错误回执,从而触发重试
3. 监听器
在SpringAmqp中,对消息的消费者进行了封装和抽象,一个普通的JavaBean中的普通方法,只要通过简单的注解,就可以成为一个消费者。
package com.linqibin.rabbitmq.spring;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class Listener {
/**
* @RabbitListener 声明这是一个消费者方法.
* @param msg
*/
@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);
}
}
- @Componet:类上的注解,注册到Spring容器
- @RabbitListener:方法上的注解,声明这个方法是一个消费者方法,需要指定下面的属性:
- bindings:指定绑定关系,可以有多个。值是@QueueBinding的数组。@QueueBinding包含下面属性:
- value:这个消费者关联的队列。值是@Queue,代表一个队列
- exchange:队列所绑定的交换机,值是@Exchange类型
- key:队列和交换机绑定的RoutingKey
- bindings:指定绑定关系,可以有多个。值是@QueueBinding的数组。@QueueBinding包含下面属性:
类似listen这样的方法在一个类中可以写多个,就代表多个消费者。
4. AmqpTemplate
Spring为AMQP提供了统一的消息处理模板:AmqpTemplate,非常方便的发送消息,其发送方法:
需要注意的是,如果在发送的时候不指定交换机,则会使用默认的交换机
package com.linqibin.rabbitmq.spring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class SendTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSend() {
String msg = "hello spring-amqp";
// 如果不指定交换机, 则会向默认的交换机发送消息
rabbitTemplate.convertAndSend("spring.test.exchange", "hello.world", msg);
}
}
运行spring boot测试类,我们发现消息已经被成功监听到了。