在 Spring Boot 项目中,可以通过添加 `spring-boot-starter-amqp` 依赖来集成 RabbitMQ

以下是关于 Spring for RabbitMQ 的详细指南,基于最新的搜索结果信息:

Spring for RabbitMQ:快速入门与使用指南

1. 添加依赖

在 Spring Boot 项目中,可以通过添加 spring-boot-starter-amqp 依赖来集成 RabbitMQ。

Maven 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 配置 RabbitMQ

application.ymlapplication.properties 文件中配置 RabbitMQ 的连接信息。

application.yml 示例

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
    virtual-host: /
3. 创建消息发送者

使用 RabbitTemplate 发送消息。

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MessageSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String message) {
        rabbitTemplate.convertAndSend("myQueue", message);
        System.out.println("Sent: " + message);
    }
}
4. 创建消息接收者

使用 @RabbitListener 注解监听队列中的消息。

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class MessageReceiver {
    @RabbitListener(queues = "myQueue")
    public void receive(String message) {
        System.out.println("Received: " + message);
    }
}
5. 测试消息发送

创建一个控制器来测试消息发送。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    private MessageSender messageSender;

    @GetMapping("/send")
    public String sendMessage() {
        messageSender.send("Hello, RabbitMQ!");
        return "Message sent!";
    }
}
6. 高级功能
6.1 发布/订阅模式

使用 TopicExchange 和通配符路由键。

配置交换机和队列

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    @Bean
    public Queue topicsQueue1() {
        return new Queue("topicsQueue1", true);
    }

    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange("topicExchange");
    }

    @Bean
    public Binding binding(Queue topicsQueue1, TopicExchange topicExchange) {
        return BindingBuilder.bind(topicsQueue1).to(topicExchange).with("*.error");
    }
}

生产者代码

@GetMapping("/topics/{routingKey}")
public String sendTopicMessage(@PathVariable String routingKey) {
    rabbitTemplate.convertAndSend("topicExchange", routingKey, "Hello from Topic!");
    return "Message sent to topic exchange!";
}

消费者代码

@Component
public class TopicListener {
    @RabbitListener(queues = "topicsQueue1")
    public void receive(String message) {
        System.out.println("Received: " + message);
    }
}
6.2 工作队列模式

多个消费者共享一个队列,消息按轮询方式分发。

生产者代码

@GetMapping("/work")
public String sendWorkMessage() {
    for (int i = 0; i < 10; i++) {
        rabbitTemplate.convertAndSend("", "workQueue", "Task " + i);
    }
    return "Tasks sent!";
}

消费者代码

@Component
public class WorkListener {
    @RabbitListener(queues = "workQueue")
    public void receive(String message) {
        System.out.println("Received task: " + message);
    }
}
7. 部署与生产环境配置

在生产环境中,需要确保 RabbitMQ 的安装和配置正确,并使用 SSL/TLS 加密通信。

配置 SSL

spring:
  rabbitmq:
    host: your-rabbitmq-server
    port: 5671
    username: your-username
    password: your-password
    virtual-host: /
    ssl:
      enabled: true
8. 更多资源

通过以上步骤,你可以在 Spring Boot 项目中快速集成 RabbitMQ,并实现消息的发送和接收。

Reference Documentation

For further reference, please consider the following sections:

Guides

The following guides illustrate how to use some features concretely:

/*
 * Copyright 2007-present the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;

public class MavenWrapperDownloader {

    private static final String WRAPPER_VERSION = "0.5.6";
    /**
     * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
     */
    private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
        + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";

    /**
     * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
     * use instead of the default one.
     */
    private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
            ".mvn/wrapper/maven-wrapper.properties";

    /**
     * Path where the maven-wrapper.jar will be saved to.
     */
    private static final String MAVEN_WRAPPER_JAR_PATH =
            ".mvn/wrapper/maven-wrapper.jar";

    /**
     * Name of the property which should be used to override the default download url for the wrapper.
     */
    private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";

    public static void main(String args[]) {
        System.out.println("- Downloader started");
        File baseDirectory = new File(args[0]);
        System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());

        // If the maven-wrapper.properties exists, read it and check if it contains a custom
        // wrapperUrl parameter.
        File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
        String url = DEFAULT_DOWNLOAD_URL;
        if(mavenWrapperPropertyFile.exists()) {
            FileInputStream mavenWrapperPropertyFileInputStream = null;
            try {
                mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
                Properties mavenWrapperProperties = new Properties();
                mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
                url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
            } catch (IOException e) {
                System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
            } finally {
                try {
                    if(mavenWrapperPropertyFileInputStream != null) {
                        mavenWrapperPropertyFileInputStream.close();
                    }
                } catch (IOException e) {
                    // Ignore ...
                }
            }
        }
        System.out.println("- Downloading from: " + url);

        File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
        if(!outputFile.getParentFile().exists()) {
            if(!outputFile.getParentFile().mkdirs()) {
                System.out.println(
                        "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
            }
        }
        System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
        try {
            downloadFileFromURL(url, outputFile);
            System.out.println("Done");
            System.exit(0);
        } catch (Throwable e) {
            System.out.println("- Error downloading");
            e.printStackTrace();
            System.exit(1);
        }
    }

    private static void downloadFileFromURL(String urlString, File destination) throws Exception {
        if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
            String username = System.getenv("MVNW_USERNAME");
            char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        }
        URL website = new URL(urlString);
        ReadableByteChannel rbc;
        rbc = Channels.newChannel(website.openStream());
        FileOutputStream fos = new FileOutputStream(destination);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        rbc.close();
    }

}

distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.amqp</groupId>
			<artifactId>spring-rabbit-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

### 如何在 IntelliJ IDEA 中添加 `spring-boot-starter-amqp` 依赖 要在 IntelliJ IDEA 中成功添加并使用 `spring-boot-starter-amqp` 依赖,可以通过以下方法实现: #### 修改项目的 `pom.xml` 文件 确保项目是一个 Maven 项目,并编辑其 `pom.xml` 文件,在 `<dependencies>` 部分添加如下代码块: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 此操作会引入 RabbitMQ 的客户端库以及 Spring AMQP 支持的相关组件[^1]。 #### 处理可能的依赖下载失败问题 如果遇到依赖无法正常下载的情况,可能是由于网络原因或者仓库配置不正确引起的。以下是解决方案: 1. **检查 Maven 设置中的镜像源** 如果当前使用的 Maven 配置指向了阿里云或其他国内镜像站点,则需要确认这些站点是否提供所需的依赖项。例如,阿里云镜像通常不会包含最新的 SNAPSHOT 版本资源。此时可以在 `pom.xml` 文件中显式声明额外的仓库地址: ```xml <!-- 添加 Spring 官方仓库 --> <repositories> <repository> <id>spring-snapshots</id> <url>https://repo.spring.io/libs-snapshot</url> </repository> </repositories> ``` 2. **清理本地缓存** 若之前尝试过加载该依赖但未成功,可能会残留一些损坏的文件于本地 `.m2/repository` 目录下。建议删除对应版本目录(如 `.../spring-boot-starter-amqp/2.x.x.RELEASE`),之后重新执行 Maven 命令刷新依赖树[^4]。 3. **强制更新依赖** 在 IntelliJ IDEA 的右侧工具栏找到 Maven 插件窗口,点击绿色循环箭头按钮以触发 “Reimport All Maven Projects”。另外也可以手动运行命令行指令完成相同目的: ```bash mvn clean install -U ``` 参数 `-U` 表示强制从远程服务器拉取最新版本数据覆盖旧版记录[^5]。 #### 刷新 IDE 并验证环境配置 完成上述更改后记得保存修改过的 XML 文档,接着回到 IntelliJ IDEA 主界面右键单击工程根节点选择菜单选项【Reload Project】或按快捷键组合 Ctrl+F9 编译整个工作区。最后观察控制台输出日志判断是否存在异常错误提示;如果没有则表明集成过程顺利完成。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值