rabbitMQ

同步调用的优点:时效性强,等待到结果后才会返回

       缺点:拓展性差,性能下降,级联失败问题

异步调用的优点:接触耦合,增强拓展性;无需等待,性能好;故障隔离;缓存消息,流量削峰填谷

     缺点:时效性差,不确定是否成功,业务安全依赖于broker的可靠性

 

rabbitMQ整体架构:

  virtual-host:因为rabbitMQ吞吐量可以达到10W,所以我们可以让多个项目公用同一个rabbitMQ。为了防止不同项目的exchange和queue不互相干扰,我们引入了virtualhost

 在发送消息的时候,exchange只负责路由,不会存储消息

 

如何在spring中使用amqp:

1.引入依赖

  <!--AMQP依赖,包含RabbitMQ-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

2.编写yml

spring:
  rabbitmq:
    host: 192.168.88.95
    port: 5672
    virtual-host: /hmall
    username: hmall
    password: 123

3.publisher(记得提前在15672中创建好queue)

@Autowired
    RabbitTemplate rabbitTemplate;
    @Test
    public void test(){
        String queueName="simple.queue";
        String message="你好呀!小兔子";
        rabbitTemplate.convertAndSend(queueName,message);
    }

4.consumer

@Component
@Slf4j
public class SpringRabbitMqListener {
    @RabbitListener(queues = "simple.queue")
    public void listener(String message) {
        log.info("收到的消息是{}",message);
    }
}

 

 

workqueue模式:多个消费者绑定一个queue,这样做可以分担压力。默认状态下消费模式类似于轮询。

当然,我们可以通过修改preFetch来进行消息推送限制:每次只能获取prefetch条消息,处理完成后才能获取下一条消息。实现分配均衡

  rabbitmq:
    listener:
      simple:
        prefetch: 1

 

交换机:接收消息,并路由到队列上

fanout交换机:广播 :将消息路由到每一个和他绑定的队列上。

direct交换机:将收到的消息根据规则去路由到指定的queue:

      queue与exchange绑定时会有一个bindingkey,发布者发送消息的时候指定具体的bindingkey,具有一致key的queue会收到消息

topic交换机:与direct大致相同,不同点为:routingKey由多个单词组成,用.分割,具有通配符:#代表一个或多个单词,*代表一个单词

 

基于Bean生成队列交换机

@Configuration
public class FanoutConfiguration {
    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange("hmall.fanout");
    }
    @Bean
    public Queue fanoutQueue1(){
        return new Queue("fanout.queue1");
    }
    @Bean
    public Binding fanoutQueue1Bind(FanoutExchange fanoutExchange,Queue fanoutQueue1){
        return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
    }
}

基于注解生成队列交换机

@RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue1",durable = "true"),
            exchange = @Exchange(name = "hmall.direct",type = ExchangeTypes.DIRECT),
            key = {"white","all"}
    ))
    public void directListener1(String message) {
        log.info("白组收到的消息是:{}",message);
    }

 

消息转换器:推荐使用json替代jdk序列化

posted on 2024-05-03 15:02  天启A  阅读(4)  评论(0编辑  收藏  举报

导航