最近面试许多面试者,都熟悉消息中间件,因此开启了学习rabbit mq的道路
首先是简单集成Rabbit MQ 到 Spring cloud中
项目搭建省略,用到了配置中心config,eurica,eurica和config配置,以及额外的项目配置此处省略
config配置主要如下:
server:
port: 8010
spring:
application:
name: order
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
# 以下都是rabbitmq默认配置
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
mybatis:
mapper-locations: classpath:/mapping/*.xml
type-aliases-package: com.training.entity
紧接着引入rabbit mq的相关依赖,在需要用到的子项目中,由于还要测试,多引用测试的starter
<!-- rabbitmq 客户端 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
发送者:此处额外知识点
@RabbitListener(queuesToDeclare = @Queue("myQueue"))与
@RabbitListener(queues = "myQueue")写法的区别,前者是如果rabbit mq中没有改队列则会自动创建,后者需要提前在rabbit mq中去创建,如果没有该消息队列会出现DeclarationException异常,如下
org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$DeclarationException: Failed to declare queue(s):[myQ1ueue]
创建方式:
@Component
@Slf4j
public class Receiver {
/**
* 接收消息
* @param hello
*/
@RabbitListener(queuesToDeclare = @Queue("myQueue"))
public void process(String hello){
log.info("Reciver: "+ hello);
}
}
接收者:
@RunWith(SpringRunner.class)
@SpringBootTest
public class Sender {
@Autowired
private AmqpTemplate template;
@Test
public void send(){
for (int i = 0; i < 100; i++) {
template.convertAndSend("myQueue", "第" + i + "条消息");
}
}
}
上图有提及Rabbit MQ,详细介绍下创建这个队列的信息
-
Durable: 是否需要持久化, true表示持久化, false为非持久化
-
AutoDelete: 是否自动删除, true表示自动删除, false为非自动删除,当队列在指定的时间内没有被使用(访问)就会被删除
-
Message TTL:使用x-message-ttl参数设置当前队列中所有消息的过期时间,即当前队列中所有的消息过期时间都一样,毫秒级别,消息的生存时间
- Max length : 队列可以容纳的消息的最大条数,超过这个条数,队列头部的消息将会被丢弃.
- Max length bytes : 队列可以容纳的消息的最大字节数
-
Overflow behaviour:队列中的消息溢出时,如何处理这些消息.要么丢弃队列头部的消息,要么拒绝接收后面生产者发送过来的所有消息.( 从上面两个参数的测试中可以看出,"drop-head" 应该是默认行为) ,官方只给了 value,没给 key . key 为 "x-overflow"
-
Dead letter exchange:该参数值为一个(死信)交换机的名称,当队列中的消息的生存期到了,或者因长度限制被丢弃时,消息会被推送到(绑定到)这台交换机(的队列中),而不是直接丢掉
-
Dead letter routing key:我理解为根据路由键值选择交换机中的队列
-
Maximum priority:设置该队列中的消息的优先级最大值.发布消息的时候,可以指定消息的优先级,优先级高的先被消费.如果没有设置该参数,那么该队列不支持消息优先级功能.也就是说,就算发布消息的时候传入了优先级的值,也不会起什么作用.
-
Lazy mode:翻译 : 设置队列为懒人模式.该模式下的队列会先将交换机推送过来的消息(尽可能多的)保存在磁盘上,以减少内存的占用.当消费者开始消费的时候才加载到内存中;如果没有设置懒人模式,队列则会直接利用内存缓存,以最快的速度传递消息.
-
Master locator:将队列设置为主位置模式,确定在节点集群上声明时队列主机所在的规则