RabbitMQ学习_day1

Spring整合RabbitMQ

Spring整合RabbitMQ 生产者实现

Spring整合RabbitMQ中生产者的实现,基本步骤为:
1、搭建环境,创建maven项目
2、导入依赖,对应的依赖内容如下所示:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.1.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId>spring-rabbit</artifactId>
        <version>2.1.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.1.7.RELEASE</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>8</source>
                <target>8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

3、在resources包下面分别创建配置文件: rabbitmq.properties以及spring-rabbitmq-producer.xml,其中rabbitmq.properties是设置RabbitMQ的相关参数,例如host,port,username以及password等,而spring-rabbitmq-producer.xml则是spring的配置文件,对应的配置文件如下所示:
rabbitmq.properties:

rabbitmq.host=localhost
rabbitmq.port=5672
rabbitmq.username=guest
rabbitmq.password=guest
rabbitmq.virtual-host=/

spring-rabbitmq-consumer.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
    <!--加载配置文件,这里的rabbitmq.properties文件位于resources/properties包下-->
    <context:property-placeholder location="classpath:/properties/rabbitmq.properties"/>

    <!-- 定义rabbitmq connectionFactory -->
    <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"/>
    <!--定义管理交换机、队列-->
    <rabbit:admin connection-factory="connectionFactory"/>

    <!--定义持久化队列,不存在则自动创建auto-declare;
    不绑定到交换机则绑定到默认交换机默认交换机类型为direct,名字为:"",
    routing key为队列的名称
    对应的配置信息如下所示:
    id: 表示的是bean的名字
    name: 队列名
    auto-declare: 队列不存在的时候,是否自动创建
    durable: 是否持久化,如果为true,表示是
    auto-delete: 是否自动删除,如果没有消费者和这个队列相连的时候,这个队列是否自动删除
    exclusive: 是否独占连接
    -->
    <rabbit:queue id="spring_queue" name="spring_queue" auto-declare="true"/>

    <!-- 广播;所有队列都能收到消息-->
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"/>

    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>

    <!--定义广播类型交换机;并绑定上述两个队列
    对应得配置信息如下所示:
    durable: 交换机是否持久化
    auto-declare: 交换机不存在的时候是否自动创建
    internal: 是否内部使用
    auto-delete: 不使用的时候,是否自动删除
    -->
    <rabbit:fanout-exchange id="spring_fanout_exchange" name="spring_fanout_exchange" auto-declare="true">
        <rabbit:bindings>
        <!--因为是广播类型,所绑定得队列都能够收到来自这个交换机的消息-->
            <rabbit:binding queue="spring_fanout_queue_1"/>
            <rabbit:binding queue="spring_fanout_queue_2"/>
        </rabbit:bindings>
    </rabbit:fanout-exchange>

    <!-- 通配符;*匹配一个单词,#匹配多个单词-->
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue_star" name="spring_topic_queue_star" auto-declare="true"/>
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue_well" name="spring_topic_queue_well" auto-declare="true"/>
    <!--定义广播交换机中的持久化队列,不存在则自动创建-->
    <rabbit:queue id="spring_topic_queue_well2" name="spring_topic_queue_well2" auto-declare="true"/>
    <!--定义一个通配符模式的交换机,其中符合对应的pattern的队列能够收到信息-->
    <rabbit:topic-exchange id="spring_topic_exchange" name="spring_topic_exchange" auto-declare="true">
        <rabbit:bindings>
            <!--*表示的是任意一个单词,#表示任意多个单词-->
            <rabbit:binding pattern="heima.*" queue="spring_topic_queue_star"/>
            <rabbit:binding pattern="heima.#" queue="spring_topic_queue_well"/>
            <rabbit:binding pattern="itcast.#" queue="spring_topic_queue_well2"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>
    
    <!--
    定向模式的交换机,只有routing Key 等于给定的值的时候,这个交换机的消息
    才可以发送给绑定的指定队列,例如如果routing Key为heima.msg,那么只能
    将消息发送给队列spring_fanout_queue_1
    -->
    <rabbit:direct-exchange id="direct_exchange" name="direct_exchange">
        <rabbit:bindings>
            <rabbit:binding key="heima.msg" queue="spring_fanout_queue_1"></rabbit:binding>
            <rabbit:binding key="heima.itcast" queue="spring_fanout_queue_1"></rabbit:binding>
        </rabbit:bindings>
    </rabbit:direct-exchange>

    <!--定义rabbitTemplate对象操作可以在代码中方便发送消息-->
    <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
</beans>

4、开始测试,在测试类中,利用RabbitTemplate调用convertAndSend方法发送消息。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/spring/spring-rabbitmq.xml")
public class SpringRabbitmqTest {
    
    
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 测试RabbitMQ的工作模式,路由key为队列名,交换机默认为""
     * 通过rabbitmqTemplate调用convertAndSend来发送信息
     */
    @Test
    public void test(){
    
    
        rabbitTemplate.convertAndSend("spring_queue", "hello world!");
    }

    /**
     * 测试RabbitMQ的广播模式,其中交换机为spring_fanout_exchange
     * 路由key为"",那么发送的消息就会发送给这个交换机绑定的所有队列
     */
    @Test
    public void testFanout(){
    
    
        rabbitTemplate.convertAndSend("spring_fanout_exchange", "", "hello fanout");
    }

    /**
     * 测试RabbitMQ中通配符模式Topic,其中交换机为spring_topic_exchange
     * 路由key是通配符pattern,那么发送的消息就会发送给路由key符合pattern
     * 模式的队列
     */
    @Test
    public void testTopic(){
    
    
        rabbitTemplate.convertAndSend("spring_topic_exchange", "heima.topic", "routing key: heima.topic");
        rabbitTemplate.convertAndSend("spring_topic_exchange", "heima.topic.msg", "routing key : heima.topic.msg");
        rabbitTemplate.convertAndSend("spring_topic_exchange", "itcast.topic", "routing key: itcast.topic");
    }
}

Spring整合RabbitMQ 消费者实现

Spring整合RabbitMQ 消费者的实现基本步骤:
1、搭建环境,创建maven项目
2、导入对应的依赖
3、在resources报下创建对应的配置文件rabbitmq.prpperties以及spring-rabbitmq-consumer.xml,对应的rabbitmq.properties的配置和上面生产者的实现一样的。
4、设置监听,定义类SpringQueueListener,使得这个类实现了接口MessageListener,重写方法onMessage,这样一旦这个类监听的队列收到了消息,那么就能立刻执行onMessage方法。对应的代码为:

public class SpringQueueListener implements MessageListener {
    
    
    @Override
    public void onMessage(Message message) {
    
    
        System.out.println("RabbitMQ中的word模式接收到的内容为: "  + new String(message.getBody()));
    }
}

5、将定义好的SpringQueueListener类添加到Spring容器中,同时需要设置这个类监听的队列。所以需要在spring-rabbitmq-consumer.xml中进行配置.所以对应的spring-rabbitmq-consumer.xml内容为:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
    <!--加载配置文件-->
    <context:property-placeholder location="classpath:/properties/rabbitmq.properties"/>

    <!-- 定义rabbitmq connectionFactory -->
    <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"/>
    <!--定义管理交换机、队列-->
    <rabbit:admin connection-factory="connectionFactory"/>

    <bean id="springQueueListener" class="com.example.listener.SpringQueueListener"></bean>
    <bean id="springFanoutListener1" class="com.example.listener.SpringFanoutListener1"></bean>
    <bean id="springFanoutListener2" class="com.example.listener.SpringFanoutListener2"></bean>
    <bean id="springTopicListener1" class="com.example.listener.SpringTopicListener1"></bean>
    <bean id="springTopicListener2" class="com.example.listener.SpringTopicListener2"></bean>
    <bean id="springTopicListener3" class="com.example.listener.SpringTopicListener3"></bean>
    <rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
    <!--一旦队列spring_queue接收到信息,就执行SpringQueueListener中onMessage方法-->
        <rabbit:listener ref="springQueueListener" queue-names="spring_queue"></rabbit:listener>
         <!--一旦队列spring_fanout_queue_1接收到信息,就执行SpringFanoutListener1中onMessage方法,下面的同理-->
        <rabbit:listener ref="springFanoutListener1" queue-names="spring_fanout_queue_1"></rabbit:listener>
        <rabbit:listener ref="springFanoutListener2" queue-names="spring_fanout_queue_2"></rabbit:listener>
        <rabbit:listener ref="springTopicListener1" queue-names="spring_topic_queue_star"></rabbit:listener>
        <rabbit:listener ref="springTopicListener2" queue-names="spring_topic_queue_well"></rabbit:listener>
        <rabbit:listener ref="springTopicListener3" queue-names="spring_topic_queue_well2"></rabbit:listener>
    </rabbit:listener-container>
</beans>

6、此时一旦启动了这个项目,那么当消息队列中存在消息,就能立刻执行对应的MessageListener实现类中的onMessage方法。或者写一个测试类,然后定义一个方法test,在这个方法中不断执行循环,当结束测试的时候,就会打印onMessage中的方法信息了:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/spring/spring-rabbitmq-consumer.xml")
public class ConsumerTest {
    
    
    //测试RabbitMQ的word模式
    @Test
    public void test(){
    
    
        while(true){
    
    

        }
    }
}

SpringBoot整合RabbitMQ

SpringBoot整合RabbitMQ 生产者实现

SpringBoot 整合RabbitMQ 生产者实现的基本步骤:
1、搭建环境,搭建SpringBoot项目
2、导入对应的依赖spring-boot-starter-amqp,对应代码为:

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

3、在application.yml中配置rabbitmq的相关信息,例如host,port,username,password等,对应的appilcation.yml代码为:

spring:
  rabbitmq:
    host: localhost
    port: 5672
    stream:
      username: guest
      password: guest
    virtual-host: /

4、定义RabbitMQ的配置类RabbitmqConfig,从而将创建队列,交换机,以及将交换机和队列进行绑定,对应的RabbitmqConfig代码为:

@Configuration
public class RabbitmqConfig {
    
    
    public static final String BOOT_FANOUT_EXCHANGE = "boot_fanout_exchange";
    public static final String BOOT_TOPIC_EXCHANGE = "boot_topic_exchange";
    public static final String BOOT_FANOUT_QUEUE_1 = "boot_fanout_queue_1";
    public static final String BOOT_FANOUT_QUEUE_2 = "boot_fanout_queue_2";
    public static final String BOOT_TOPIC_QUEUE_1 = "boot_topic_queue_1";
    public static final String BOOT_TOPIC_QUEUE_2 = "boot_topic_queue_2";

    //创建交换机
    @Bean("boot_fanout_exchange")//fanoutExchange是bean的名字
    public Exchange fanoutExchange(){
    
    
        //BOOT_FANOUT_EXCHANGE是交换机的名字
        return ExchangeBuilder.fanoutExchange(BOOT_FANOUT_EXCHANGE).build();
    }

    @Bean("boot_topic_exchange")
    public Exchange topicExchange(){
    
    
        return ExchangeBuilder.topicExchange(BOOT_TOPIC_EXCHANGE).build();
    }

    //创建队列
    @Bean("boot_fanout_queue_1")
    public Queue fanoutQueue1(){
    
    
        return QueueBuilder.durable(BOOT_FANOUT_QUEUE_1).build();
    }
    @Bean("boot_fanout_queue_2")
    public Queue fanoutQueue2(){
    
    
        return QueueBuilder.durable(BOOT_FANOUT_QUEUE_2).build();
    }

    @Bean("boot_topic_queue_1")
    public Queue topicQueue1(){
    
    
        return QueueBuilder.durable(BOOT_TOPIC_QUEUE_1).build();
    }
    @Bean("boot_topic_queue_2")
    public Queue topicQueue2(){
    
    
        return QueueBuilder.durable(BOOT_TOPIC_QUEUE_2).build();
    }
    //让交换机和队列进行绑定
    @Bean
    public Binding bindingQueueAndExchange1(@Qualifier(BOOT_FANOUT_QUEUE_1) Queue queue, @Qualifier(BOOT_FANOUT_EXCHANGE) Exchange exchange){
    
    
        return BindingBuilder.bind(queue) //队列名
                .to(exchange) //要绑定的交换机
                .with("") //routing key为 ""
                .noargs(); //构造Binding对象的时候没有参数
    }

    @Bean
    public Binding bindingQueueAndExchange2(@Qualifier(BOOT_FANOUT_QUEUE_2) Queue queue, @Qualifier(BOOT_FANOUT_EXCHANGE) Exchange exchange){
    
    
        return BindingBuilder.bind(queue) //队列名
                .to(exchange) //要绑定的交换机
                .with("") //routing key为 ""
                .noargs(); //构造Binding对象的时候没有参数
    }

    @Bean
    public Binding bindingQueueAndExchange3(@Qualifier(BOOT_TOPIC_QUEUE_1) Queue queue, @Qualifier(BOOT_TOPIC_EXCHANGE) Exchange exchange){
    
    
        return BindingBuilder.bind(queue) //队列名
                .to(exchange) //要绑定的交换机
                .with("heima.*") //routing key为 heima.*
                .noargs(); //构造Binding对象的时候没有参数
    }

    @Bean
    public Binding bindingQueueAndExchange4(@Qualifier(BOOT_TOPIC_QUEUE_2) Queue queue, @Qualifier(BOOT_TOPIC_EXCHANGE) Exchange exchange){
    
    
        return BindingBuilder.bind(queue) //队列名
                .to(exchange) //要绑定的交换机
                .with("heima.#") //routing key为 heima.#
                .noargs(); //构造Binding对象的时候没有参数
    }
}

5、在测试类中利用RabbitTemplate调用converstAndSend方法发送信息,测试类代码为:

@SpringBootTest
public class ProducerTest {
    
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Test
    public void testFanout(){
    
    
        rabbitTemplate.convertAndSend(RabbitmqConfig.BOOT_FANOUT_EXCHANGE, "", "boot_fanout_exchange发送的消息");
    }

    @Test
    public void testTopic(){
    
    
        rabbitTemplate.convertAndSend(RabbitmqConfig.BOOT_TOPIC_EXCHANGE, "heima.topic", "通配符为heima.topic");
        rabbitTemplate.convertAndSend(RabbitmqConfig.BOOT_TOPIC_EXCHANGE, "heima.topic.msg", "通配符为heima.topic.msg");
    }
}

SpringBoot整合RabbitMQ 消费者实现

SpringBoot 整合RabbitMQ 实现消费者的对应步骤为:
1、搭建环境,创建SpringBoot项目
2、导入依赖spring-boot-starter-amqp
3、在application.yml中配置rabbitmq的基本信息,例如host,port,username,password等
4、设置监听,定义类RabbitmqListener,并将这个类添加到Spring容器中,此时利用注解@RabbitListener(queues = "xxx"),来监听队列名为xxxx的队列,一旦这个队列收到了消息,那么就会执行这个注解修饰的方法,对应的代码为:

@Component
public class RabbitmqListener {
    
    

    @RabbitListener(queues = "boot_fanout_queue_1")
    public void fanoutListen1(Message message){
    
    
        System.out.println("队列boot_fanout_queue_1接收到的内容为: " + new String(message.getBody()));
    }
    @RabbitListener(queues = "boot_fanout_queue_2")
    public void fanoutListen2(Message message){
    
    
        System.out.println("队列boot_fanout_queue_2接收到的内容为: " + new String(message.getBody()));
    }

    @RabbitListener(queues = "boot_topic_queue_1")
    public void topicListen1(Message message){
    
    
        System.out.println("队列boot_topic_queue_1接收到的内容为: " + new String(message.getBody()));
    }
    @RabbitListener(queues = "boot_topic_queue_2")
    public void topicListen2(Message message){
    
    
        System.out.println("队列boot_topic_queue_2接收到的内容为: " + new String(message.getBody()));
    }

}

然后启动这个项目,如果队列中存在消息,那么就会执行RabbitmqListener中对应的方法。

猜你喜欢

转载自blog.csdn.net/weixin_46544385/article/details/128651290