SpringBoot integrates RabbitMQ

Directory

1. Spring integrates RabbitMQ

1. Create a producer

2. Create a consumer

2. SpringBoot integrates RabbitMQ

1. Create a producer

2. Create a consumer


1. Spring integrates RabbitMQ

1. Create producer

1. Create a project

2. Add dependencies

<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.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

3. Write configuration

rabbitmq.properties file

rabbitmq.host=192.168.138.129
rabbitmq.port=5672
rabbitmq.username=admin
rabbitmq.password=admin
rabbitmq.virtual-host=/

spring-rabbitmq-producer.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">
    <!--Load configuration file-->
    <context:property-placeholder location="classpath:rabbitmq.properties"/>

    <!-- Define rabbitmq connectionFactory -->
    <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq. username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"/>
    <!--Define management switches, queues-->
    <rabbit:admin connection-factory="connectionFactory"/>

    <!--Define the persistent queue, if it does not exist, it will be created automatically; if it is not bound to the switch, it will be bound to the default switch
    The default switch type is direct, the name is: "", the routing key is the name of the queue
    -->
        <!--
        id: the name of the bean
        name: the name of the queue
        auto-declare: automatically created
        auto-delete: Automatically delete. After the last consumer disconnects from the queue, the queue is automatically deleted
        exclusive: whether exclusive
        durable: Whether to persist
        -->

    <rabbit:queue id="spring_queue" name="spring_queue" auto-declare="true"/>

    <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~Broadcast; all queues can receive messages~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~ -->
    <!--Define the persistent queue in the broadcast switch, if it does not exist, it will be created automatically-->
    <rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"/>

    <!--Define the persistent queue in the broadcast switch, if it does not exist, it will be created automatically-->
    <rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>

    <!--Define the broadcast type switch; and bind the above two queues-->
    <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>

    <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Wildcards; * matches one word, # matches multiple words ~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~ -->
    <!--Define the persistent queue in the broadcast switch, if it does not exist, it will be created automatically-->
    <rabbit:queue id="spring_topic_queue_star" name="spring_topic_queue_star" auto-declare="true"/>
    <!--Define the persistent queue in the broadcast switch, if it does not exist, it will be created automatically-->
    <rabbit:queue id="spring_topic_queue_well" name="spring_topic_queue_well" auto-declare="true"/>
    <!--Define the persistent queue in the broadcast switch, if it does not exist, it will be created automatically-->
    <rabbit:queue id="spring_topic_queue_well2" name="spring_topic_queue_well2" auto-declare="true"/>

    <rabbit:topic-exchange id="spring_topic_exchange" name="spring_topic_exchange" auto-declare="true">
        <rabbit:bindings>
            <rabbit:binding pattern="zhangsan.*" queue="spring_topic_queue_star"/>
            <rabbit:binding pattern="zhangsan.#" queue="spring_topic_queue_well"/>
            <rabbit:binding pattern="lisi.#" queue="spring_topic_queue_well2"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>

    <!--Defining the rabbitTemplate object operation can send messages conveniently in the code-->
    <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
</beans>

4. Write code to send message

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

    @Test
    public void testHelloWorld(){
        rabbitTemplate.convertAndSend("spring_queue","hello world spring...");
    }

    /**
     * Send fanout message
     */
    @Test
    public void testFanout(){
        //2. Send message

        rabbitTemplate.convertAndSend("spring_fanout_exchange","","spring fanout....");
    }

    /**
     * Send topic message
     */
    @Test
    public void testTopics(){
        //2. Send message

        rabbitTemplate.convertAndSend("spring_topic_exchange","zhangsan.heiihei.haha","spring topic....");
    }

}

result

2. Create consumer

1. Create a project

2. Add dependencies

<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.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

3. Write configuration

<?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">
    <!--Load configuration file-->
    <context:property-placeholder location="classpath:rabbitmq.properties"/>

    <!-- Define rabbitmq connectionFactory -->
    <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq. username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"/>

    <bean id="springQueueListener" class="com.rabbitmq.listener.SpringQueueListener"/>
   <!-- <bean id="fanoutListener1" class="com.rabbitmq.listener.FanoutListener1"/>
    <bean id="fanoutListener2" class="com.rabbitmq.listener.FanoutListener2"/>
    <bean id="topicListenerStar" class="com.rabbitmq.listener.TopicListenerStar"/>
    <bean id="topicListenerWell" class="com.rabbitmq.listener.TopicListenerWell"/>
    <bean id="topicListenerWell2" class="com.rabbitmq.listener.TopicListenerWell2"/>-->
    <rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
        <rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>
       <!-- <rabbit:listener ref="fanoutListener1" queue-names="spring_fanout_queue_1"/>
        <rabbit:listener ref="fanoutListener2" queue-names="spring_fanout_queue_2"/>
        <rabbit:listener ref="topicListenerStar" queue-names="spring_topic_queue_star"/>
        <rabbit:listener ref="topicListenerWell" queue-names="spring_topic_queue_well"/>
        <rabbit:listener ref="topicListenerWell2" queue-names="spring_topic_queue_well2"/>-->
    </rabbit:listener-container>
</beans>

4. Write a message listener

public class SpringQueueListener implements MessageListener {
    @Override
    public void onMessage(Message message) {
        //print message
        System.out.println(new String(message.getBody()));
    }
}

2. SpringBoot integrates RabbitMQ

1. Create a producer

1. Create a springboot project

2. Add dependencies

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

3. Configure the yml file

spring:
  rabbitmq:
    host: 192.168.138.129
    username: admin
    password: admin
    virtual-host: /
    port: 5672

4. Define switches, queues and binding relationships

@Configuration
public class RabbitMQConfig {

    //Define the switch name
    public static final String EXCHANGE_NAME = "boot_topic_exchange";
    //Define the queue name
    public static final String QUEUE_NAME = "boot_queue";

    //create switch
    @Bean("bootExchange")
    public Exchange bootExchange(){
        //durable: Whether to persist
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }

    //Create queue
    @Bean("bootQueue")
    public Queue bootQueue(){
        return QueueBuilder.durable(QUEUE_NAME).build();
    }

    //3. Queue and interactive machine binding relationship Binding
    /*
        1. Know which queue
        2. Know which switch
        3. routing key
     */
    @Bean
    public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    }

}

5. Inject RabbitTemplate, call methods, and send messages

@SpringBootTest
class ProducerSpringbootApplicationTests {

    //1. Inject RabbitTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    void contextLoads() {
    }

    @Test
    public void testSend(){
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","boot mq hello~~~");
    }
}

2. Create a consumer

1. Create a springboot project

2. Add dependencies

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

3. Modify the configuration file

spring:
  rabbitmq:
    host: 192.168.138.129
    username: admin
    password: admin
    virtual-host: /
    port: 5672

4. Define the listening class and use the @RabbitListener annotation to complete the queue monitoring

@Component
public class RabbimtMQListener {

    @RabbitListener(queues = "boot_queue")
    public void ListenerQueue(Message message){
        System.out.println(new String(message.getBody()));
    }

}

Delete message queue