1. 程式人生 > >SpringBoot實戰(八)之RabbitMQ

SpringBoot實戰(八)之RabbitMQ

ext except rri gis tail spi print 區別 div

什麽是RabbitMQ?

RabbitMQ 是一個消息代理。它的核心原理非常簡單:接收和發送消息。你可以把它想像成一個郵局:你把信件放入郵箱,郵遞員就會把信件投遞到你的收件人處。在這個比喻中,RabbitMQ 就扮演著郵箱、郵局以及郵遞員的角色。

RabbitMQ 和郵局的主要區別是,它不是用來處理紙張的,它是用來接收、存儲和發送消息(message)這種二進制數據的。

本文主要演示是Springboot+RabbitMQ簡單整合+實例說明

關於安裝RabbitMQ,由於RabbitMQ是用Erlang語言寫的,首先必須安裝Erlang的環境。

RabbitMQ在Window下的安裝可以參考該博文鏈接:https://blog.csdn.net/weixin_39735923/article/details/79288578

該博文十分清楚詳細,我就不多說了。

下面進入示例:

一、maven依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>
4.0.0</modelVersion> <groupId>org.springframework</groupId> <artifactId>gs-messaging-rabbitmq</artifactId> <version>0.1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</
artifactId> <version>1.5.8.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

二、編寫Receive

package hello;

import java.util.concurrent.CountDownLatch;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    private CountDownLatch latch = new CountDownLatch(1);

    public void receiveMessage(String message) {
        System.out.println("Received <" + message + ">");
        latch.countDown();
    }

    public CountDownLatch getLatch() {
        return latch;
    }

}

Receiver是一個簡單的POJO,它定義了一種接收消息的方法。當你註冊它以接收消息時,你可以將其命名為任何你想要的名稱。

為方便起見,這個POJO也有一個CountDownLatch這允許它發信號通知接收到消息。這是你不太可能在生產應用程序中實現的。

註冊監聽器並發送消息

Spring AMQP RabbitTemplate提供了使用RabbitMQ發送和接收消息所需一切。具體來說,您需要配置:

  • 消息偵聽器容器

  • 聲明隊列,交換以及它們之間的綁定

  • 用於發送一些消息以測試偵聽器的組件

三、編寫Runner

package hello;

import java.util.concurrent.TimeUnit;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class Runner implements CommandLineRunner {

    private final RabbitTemplate rabbitTemplate;
    private final Receiver receiver;

    public Runner(Receiver receiver, RabbitTemplate rabbitTemplate) {
        this.receiver = receiver;
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Sending message...");
        rabbitTemplate.convertAndSend(Application.topicExchangeName, "foo.bar.baz", "Hello from RabbitMQ!");
        receiver.getLatch().await(10000, TimeUnit.MILLISECONDS);
    }

}

四、編寫配置文件

spring.application.name=spirng-boot-rabbitmq
 
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

五、編寫啟動類

package hello;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

    static final String topicExchangeName = "spring-boot-exchange";

    static final String queueName = "spring-boot";

    @Bean
    Queue queue() {
        return new Queue(queueName, false);
    }

    @Bean
    TopicExchange exchange() {
        return new TopicExchange(topicExchangeName);
    } 

    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("foo.bar.#");
    }

    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
            MessageListenerAdapter listenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Application.class, args).close();
    }

}

Spring Boot會自動創建連接工廠和RabbitTemplate,從而減少您必須編寫的代碼量。

listenerAdapter()方法中定義的bean在定義的容器中註冊為消息偵聽器container()它將偵聽“spring-boot”隊列中的消息。因為Receiver該類是POJO,所以需要將其包裝在MessageListenerAdapter指定要調用的位置receiveMessage

main()方法通過創建Spring應用程序上下文來啟動該過程。這將啟動消息偵聽器容器,該容器將開始偵聽消息。Runner然後會自動執行一個bean:它RabbitTemplate從應用程序上下文中檢索並發送“Hello from RabbitMQ!” “spring-boot”隊列中的消息。最後,它關閉Spring應用程序上下文,應用程序結束。

補充說明:JMS隊列和AMQP隊列具有不同的語義。例如,JMS僅向一個使用者發送排隊的消息。雖然AMQP隊列執行相同的操作,但AMQP生成器不會將消息直接發送到隊列。相反,消息被發送到交換機,交換機可以轉到單個隊列,或扇出到多個隊列,模仿JMS主題的概念。

SpringBoot實戰(八)之RabbitMQ