RabbitMQ:SpringAMQP 入门案例

目录


一、概述

这是一篇Java集成RabbitMQ的入门案例,在这里我们做一个小案例,来体会一下RabbitMQ的魅力。

首先我们要做的就是创建一个生产者一个消费者:

  1. 生产者直接向RabbitMQ的队列(Queue)simple.queue中发送消息。
  2. 消费者负责接收队列(Queue)simple.queue发送过来的消息。

生产者源码
消费者源码

二、基础配置

当我们的生产者要发送和接收消息时,首先需要再RabbitMQ中创建一个通道。

三、生产者

  1. 加载POM文件
xml 复制代码
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-amqp</artifactId>
	</dependency>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
	</dependency>
</dependencies>
  1. 配置YML文件
yml 复制代码
server:
  port: 8021
spring:
  #给项目来个名字
  application:
    name: rabbitmq-provider
  #配置rabbitMq 服务器
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: admin
    password: admin
    virtualHost: /mamf
    connection-timeout: 5000
    requested-heartbeat: 30
  1. 在Test中编写测试代码
java 复制代码
package com.ming;

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
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSend() {
        for (int i = 0; i < 10; i++) {
            String queueName = "simple.queue";  // 队列名称
            String messahe = String.format("hello %s, spring amqp!", i + 1);  // 消息
            rabbitTemplate.convertAndSend(queueName, messahe);  // 发送
        }
    }
}

四、消费者

消费者的前两部分与生产者是一样的,消费者需要创建一个监听,用于监听simple.queue队列。

java 复制代码
package com.ming.listens;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitmqListen {
    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueue(String message){
        System.out.println(String.format("消费者收到了simple.queue: %s", message));
    }
}

当从生产者发送消息时,消费者就会监听到数据。

相关推荐
caibixyy6 小时前
Spring Boot 整合 Redisson 实现分布式锁:实战指南
spring boot·分布式·后端
sheji34167 小时前
【开题答辩全过程】以 springboot高校社团管理系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
Terio_my7 小时前
Spring Boot 集成 Redis 缓存解决方案
spring boot·redis·缓存
相与还8 小时前
IDEA+SpringBoot实现远程DEBUG到本机
java·spring boot·intellij-idea
Terio_my8 小时前
Spring Boot 缓存技术详解
spring boot·后端·缓存
caibixyy9 小时前
Spring Boot 集成 Kafka 详解
spring boot·kafka
Terio_my10 小时前
Spring Boot 整合 Elasticsearch
spring boot·后端·elasticsearch
majunssz12 小时前
深入剖析Spring Boot依赖注入顺序:从原理到实战
java·数据库·spring boot
Terio_my12 小时前
Spring Boot 缓存与验证码生成
spring boot·spring·缓存
稚辉君.MCA_P8_Java13 小时前
DeepSeek Java 单例模式详解
java·spring boot·微服务·单例模式·kubernetes