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));
    }
}

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

相关推荐
用户3169353811833 小时前
如何从零编写一个 Spring Boot Starter
spring boot
程序员晓琪21 小时前
约定大于配置:基于 Java 包名自动生成 API 版本路由的最佳实践
java·spring boot·后端
Flittly21 小时前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
用户3521802454752 天前
🎆从 Prompt 到 Skill:让 Spring AI Agent 学会"装新技能"
人工智能·spring boot·ai编程
用户3521802454755 天前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
昵称为空C5 天前
手撸一个动态 SQL 执行引擎:不重启服务,在线增删改查任意数据库
spring boot·后端
霸道流氓气质6 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
于先生吖6 天前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端
Flittly6 天前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring