Spring Boot 集成 RabbitMQ 實戰


Spring Boot 集成 RabbitMQ 實戰

特別說明:
本文主要參考了程序員 DD 的博客文章《Spring Boot中使用RabbitMQ》,在此向原作者表示感謝。

Mac 上 RabbitMQ 的安裝

使用 brew 命令安裝 RabbitMQ

這樣子安裝的話,RabbitMQ 的腳本是安裝到 /usr/local/sbin 這個目錄里的,並且不會自動添加到你的 PATH 里,所以要先添加下。

PATH=$PATH:/usr/local/sbin
export PATH=/usr/local/bin:/usr/local/sbin:${PATH}

補充說明:sublime .zshrc ,.zshrc 這個文件可以配置環境變量。

啟動命令

rabbitmq-server

我們將會看到:

在瀏覽器中輸入 http://localhost:15672/,用戶名和密碼都是 guest 。

Spring Boot 集成 RabbitMQ 實戰

下面我們使用 Spring Boot 集成 RabbitMQ 模塊,初步體驗一下 MQ。以下的例子只是一個 HelloWorld ,讓我們簡單認識 RabbitMQ 的發送消息和接收消息。

示例代碼:

特別注意:Gradle 構建中一定要使用 spring-boot 的 plugin。

添加 Spring-Boot 插件的方法

在 build.gradle 文件中添加如下配置片段:

buildscript {
    ext {
        springBootVersion = '1.4.2.RELEASE'
    }
    repositories {
        // NOTE: You should declare only repositories that you need here
        mavenLocal()
        mavenCentral()
        maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}
        maven { url "http://repo.spring.io/release" }
        maven { url "http://repo.spring.io/milestone" }
        maven { url "http://repo.spring.io/snapshot" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'idea'
apply plugin: 'spring-boot'

補充說明:如果想設置阿里巴巴的 nexus 倉庫為中央倉庫,可以把如下的代碼片段粘貼到 build.gradle 文件的第 1 行:

allprojects {
    repositories {
        maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}
    }
}

1、引入 spring-boot-starter-amqp 模塊;

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-amqp', version: '1.3.0.M2'
}

還可以配置 application.properties

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

2、編寫 RabbitMQ 的配置類

/**
 * 特別要說明的是:如果在配置文件中聲明了 Queue 對象,就不用在 RabbitMQ 的管理員頁面創建隊列(Queue)了。
 * Created by liwei on 17/3/12.
 */
@Configuration
public class MqConfig {
    /**
     * 聲明接收字符串的隊列
     *
     * @return
     */
    @Bean
    public Queue stringQueue() {
        return new Queue("my-queue");
    }

    /**
     * 聲明接收 User 對象的隊列
     *
     * @return
     */
    @Bean
    public Queue userQueue() {
        return new Queue("my-user");
    }
}

補充說明:RabbitMQ 管理平台添加隊列的方法。
RabbitMQ 管理平台添加隊列的方法

特別要說明的是:如果在配置文件中聲明了 Queue 對象,就不用在 RabbitMQ 的管理員頁面創建隊列(Queue)了。

3、配置 RabbitMQ 的監聽器(即接收 MQ 消息的配置)

很簡單,使用 @RabbitListener(queues = "my-queue") 注解就可以了。

@Component
public class Receiver {

    @RabbitListener(queues = "my-queue")
    public void receiveMessage(String message){
        System.out.println("接收到的字符串消息是 => " + message);
    }


    @RabbitListener(queues = "my-user")
    public void receiveObject(User user){
        System.out.println("------ 接收實體對象 ------");
        System.out.println("接收到的實體對象是 => " + user);
    }
}

4、編寫實體類

特別要注意:實體類一定要實現序列化接口,才可以在網絡中傳輸。

/**
 * 特別注意:實體類一定要實現序列化接口,才可以在網絡中傳輸
 * Created by liwei on 17/4/25.
 */
public class User implements Serializable {

    private final static Long serialVersionUID = 1L;

    private Integer id;
    private String username;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

5、編寫啟動類

/**
 * 用於測試的控制類
 * Created by liwei on 17/3/12.
 */
@RestController
public class SendMQController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * http://localhost:8080/send?message=hello
     *
     * @param message
     * @return
     */
    @RequestMapping("/send")
    public String sendMQ(String message) {
        rabbitTemplate.convertAndSend("my-queue", message);
        return "ok";
    }

    /**
     * http://localhost:8080/send/user
     *
     * @return
     */
    @RequestMapping("/send/user")
    public String sendUser() {
        User user = new User();
        user.setId(1);
        user.setUsername("liwei");
        user.setPassword("123456");
        rabbitTemplate.convertAndSend("my-user", user);
        return "OK";
    }

}

6、測試方法

啟動 MyRabbitMqApplication 的 Main 方法,容器啟動以后,訪問:
http://localhost:8080/send?message=hello
http://localhost:8080/send/user
觀察控制台的輸出。

源代碼在 GitHub 上的下載地址:
https://github.com/weimingge14/03-springboot-rabbitmq


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM