欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > springboot整合rabbitmq

springboot整合rabbitmq

2025/2/22 2:11:24 来源:https://blog.csdn.net/qq_37069064/article/details/145085036  浏览:    关键词:springboot整合rabbitmq

1. 添加依赖

首先,在你的 pom.xml 文件中添加 RabbitMQ 的依赖:

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

2. 配置 RabbitMQ 连接

在 application.properties 或 application.yml 文件中配置 RabbitMQ 的连接信息:

# RabbitMQ 连接地址

spring:rabbitmq:host: 127.0.0.1port: 5672username: adminpassword: admin

3. 创建 RabbitMQ 配置类

创建一个配置类来定义队列、交换器和绑定关系:

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RabbitMQConfig {public static final String QUEUE_NAME = "testQueue";public static final String EXCHANGE_NAME = "testExchange";public static final String ROUTING_KEY = "testRoutingKey";@Beanpublic Queue queue() {return new Queue(QUEUE_NAME, false);}@Beanpublic TopicExchange exchange() {return new TopicExchange(EXCHANGE_NAME);}@Beanpublic Binding binding(Queue queue, TopicExchange exchange) {return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY);}
}

4. 创建消息生产者

创建一个服务类来发送消息到 RabbitMQ:

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class RabbitMQProducer {@Autowiredprivate RabbitTemplate rabbitTemplate;public void sendMessage(String message) {rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.ROUTING_KEY, message);}
}

5. 创建消息消费者

创建一个监听器类来接收消息:

 

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Component
public class RabbitMQConsumer {@RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)public void receiveMessage(String message) {System.out.println("Received message: " + message);}
}

6. 测试 RabbitMQ 整合

你可以编写一个简单的测试类来验证 RabbitMQ 的整合是否成功:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class RabbitMQTest {@Autowiredprivate RabbitMQProducer rabbitMQProducer;@Testpublic void testRabbitMQ() {String message = "Hello RabbitMQ";rabbitMQProducer.sendMessage(message);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词