springboot使用MQ

本文介绍了如何在SpringBoot项目中集成RabbitMQ,包括添加依赖、配置MQ、创建消息生产者和消费者,以及通过TopicExchange实现消息路由。通过示例代码展示了消息发送和接收的实现过程。
摘要由CSDN通过智能技术生成

springboot使用MQ

@author 李思文

@company 博思软件

@createdTime 2020/2/21

  1. 现在pom文件中加入依赖
<!-- MQ依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. 配置文件中加入mq相关配置
spring:
# rabbitmq配置
  rabbitmq:
#   mq地址
    host: 172.0.0.1
#   mq端口号
    port: 5672
#   mq账号
    username: devmq
#   mq密码
    password: devmq
  1. mq配置-消息生产
/**
 * @ProjectName: mqdemo
 * @ClassName: MessageProducer
 * @Description: 向mq指定队列中放消息
 * @Author: lisiwen
 * @Date: 2020/2/21 13:28
 **/
@Component
public class MessageProducer {
   
    private final Logger log = LoggerFactory.getLogger(this.getClass()
使用MQ原生API创建生产者和消费者可以分为以下几个步骤: 1. 引入MQ客户端依赖 在pom.xml文件中添加如下依赖: ``` <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.7.3</version> </dependency> ``` 2. 创建连接工厂 ```java ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setUsername("guest"); factory.setPassword("guest"); ``` 3. 创建连接 ```java Connection connection = factory.newConnection(); ``` 4. 创建通道 ```java Channel channel = connection.createChannel(); ``` 5. 创建队列 ```java String queueName = "hello"; channel.queueDeclare(queueName, false, false, false, null); ``` 6. 创建生产者 ```java String message = "Hello World!"; channel.basicPublish("", queueName, null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); ``` 7. 创建消费者 ```java channel.basicConsume(queueName, true, (consumerTag, message) -> { String msg = new String(message.getBody(), "UTF-8"); System.out.println("Received message: " + msg); }, consumerTag -> {}); ``` 完整代码示例: ```java import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class ProducerConsumerExample { public static void main(String[] args) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setUsername("guest"); factory.setPassword("guest"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String queueName = "hello"; channel.queueDeclare(queueName, false, false, false, null); String message = "Hello World!"; channel.basicPublish("", queueName, null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.basicConsume(queueName, true, (consumerTag, message) -> { String msg = new String(message.getBody(), "UTF-8"); System.out.println("Received message: " + msg); }, consumerTag -> {}); channel.close(); connection.close(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值