springboot整合rabbitMQ系列2 演示DirectExchange,TopicExchange,FanoutExchange交换机 发送和接收消息

1 添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2 配置application.yml文件

server:
  port: 8021
spring:
  #给项目来个名字
  application:
    name: rabbitmq-test
  #配置rabbitMq 服务器
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: need
    password: 123456
    #虚拟host 可以不设置,使用server默认host
    virtual-host: /testhost

3 编写配置队列,交换机,绑定的类,这里以fanoutExchange为列,其他的交换机类似

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *  1 创建三个队列 :fanout.A   fanout.B  fanout.C
 *  2 定义交换机
 *  3 将三个队列都绑定在交换机 fanoutExchange 上
 *  因为是扇型交换机, 路由键无需配置,配置也不起作用
 */
@Configuration
public class FanoutRabbitConfig {

    // durable:是否持久化,默认是false,持久化队列:会被存储在磁盘上,当消息代理重启时仍然存在,暂存队列:当前连接有效
    // exclusive:默认也是false,只能被当前创建的连接使用,而且当连接关闭后队列即被删除。此参考优先级高于durable
    // autoDelete:是否自动删除,当没有生产者或者消费者使用此队列,该队列会自动删除。
    //一般设置一下队列的持久化就好,其余两个就是默认false
    @Bean
    public Queue queueA() {
        return new Queue("fanout.A",true);
    }

    @Bean
    public Queue queueB() {
        return new Queue("fanout.B",true);
    }

    @Bean
    public Queue queueC() {
        return new Queue("fanout.C",true);
    }

    @Bean
    //DirectExchange Direct交换机
    //TopicExchange Topic交换机
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange",true,false);
    }

    @Bean
    Binding bindingExchangeA() {
        return BindingBuilder.bind(queueA()).to(fanoutExchange());

        //将队列和交换机绑定, 并设置用于路由键 (Direct交换机,Topic交换机使用)
        //return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with("TestDirectRouting");
    }

    @Bean
    Binding bindingExchangeB() {
        return BindingBuilder.bind(queueB()).to(fanoutExchange());
    }

    @Bean
    Binding bindingExchangeC() {
        return BindingBuilder.bind(queueC()).to(fanoutExchange());
    }
}

4 发送消息

import cn.huawei.rabbitmqtest1.pojo.User;
import com.alibaba.fastjson.JSON;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class RabbitmqTest1ApplicationTests_1 {

    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

    @Test
    void test_1() {
        for (int i = 1; i <= 3; i++) {
            User user = new User(i + "", "小明 " + i);
            rabbitTemplate.convertAndSend("fanoutExchange", "", JSON.toJSONString(user));
        }
    }

    @Test
    public void test_2() {
        for (int i = 1; i <= 3; i++) {
            User user = new User(i + "", "张三 " + i);
            rabbitTemplate.convertAndSend("TestTopicExchange", "news.chongqing", JSON.toJSONString(user));
        }
    }

    @Test
    public void test_3() {
        for (int i = 1; i <= 3; i++) {
            User user = new User(i + "", "陈四 " + i);
            rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", JSON.toJSONString(user));
        }
    }

}

5 接收消息

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 此代码添加 在消费者的项目中
 */
@Configuration
public class RabbitmqGlobalConfig {

    /**
     * 当发送的消息为pojo时,为报转换异常
     * 解决方法:添加这个类进行序列化解析
     * 会自动识别
     * @param objectMapper json序列化实现类
     * @return mq 消息序列化工具
     */
    @Bean
    public MessageConverter jsonMessageConverter(ObjectMapper objectMapper) {
        return new Jackson2JsonMessageConverter(objectMapper);
    }

}


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class FanoutReceiverA {

    /**
     * 注意:后4个参数,需要生产者发送消息时加上,否则为报错,注解里添加 required=false 或 删除参数
     */
    @RabbitListener(queues = "fanout.A")
    public void process(Message message,
                        Channel channel,
                        @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                        @Header(AmqpHeaders.MESSAGE_ID) String messageId,
                        @Header(AmqpHeaders.CONSUMER_TAG) String consumerTag,
                        CorrelationData correlationData) {
       
        System.out.println("FanoutReceiverA消费者收到消息  : " +new String(message.getBody()));
    }
}


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class FanoutReceiverB {

    /**
     * 注意:后4个参数,需要生产者发送消息时加上,否则为报错,注解里添加 required=false 或 删除参数
     */
    @RabbitListener(queues = "fanout.B")
    public void process(Message message,
                        Channel channel,
                        @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                        @Header(AmqpHeaders.MESSAGE_ID) String messageId,
                        @Header(AmqpHeaders.CONSUMER_TAG) String consumerTag,
                        CorrelationData correlationData) {
        
        System.out.println("FanoutReceiverB消费者收到消息  : " +new String(message.getBody()));
    }
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个方便快捷的轻量级框架,提供了许多便利的功能和特性,其中就包括了 RabbitMQ整合功能。 RabbitMQ 是一个广泛使用的消息队列系统,具有高可靠性和可扩展性,能够在分布式系统中实现异步通信、解耦和任务调度等功能,因此对于分布式系统而言具备非常重要的价值。 在Spring Boot中,整合RabbitMQ 可以通过以下步骤完成: 1. 添加 RabbitMQ 的相关依赖:在 pom.xml 文件中添加 spring-boot-starter-amqp 依赖。 2. 配置 RabbitMQ 相关信息:通过 application.yml 或 application.properties 配置文件配置RabbitMQ 的基本信息,例如:连接地址、用户名、密码等。 3. 创建 RabbitMQ 模板:通过 RabbitTemplate 类提供的方法向 RabbitMQ 发送消息接收响应信息。 4. 创建 Exchange 和 Queue:在 RabbitMQ 中创建 Exchange 和 Queue,Exchange 用于将消息路由到指定的 Queue 中。 5. 编写发送消息的代码:通过 RabbitTemplate 提供的方法send()发送消息,可以是简单字符串/对象/json等。 至此,我们已经实现了一个简单的 RabbitMQ 消息发送程序。但是在实际应用场景中,还需要具备更进一步完善的功能,例如:消息确认、消息持久化、消费者监听等功能,这些可以通过配置listener容器、消息确认机制以及使用DurableQueue,DurableExchange等参数来实现。 总之,RabbitMQ’s and Spring Boot的集成非常方便和快捷。通过简单的配置和实现,我们就可以使用 RabbitMQ 在分布式系统中实现异步通信、解决问题、任务调度等功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值