SpringBoot3整合RabbitMQ之二_简单队列模型案例
文章目录
- SpringBoot3整合RabbitMQ之二_简单队列模型案例
- 1. 简单队列模型
- 1. 消息发布者
- 1. 创建简单队列的配置类
- 2. 发布消费Controller
- 2. 消息消费者
- 3. 输出结果
1. 简单队列模型
简单队列模型就是点对点发布消息,有三个角色
P(Publisher): 消息发布者
Queue: 存储消息的队列
C(Consumer): 消息消费者
1. 消息发布者
1. 创建简单队列的配置类
package com.happy.msg.config;import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** <p>** @Description: 简单消息队列创建配置类 <br>* </p>* @Datetime: 2024/3/27 18:18* @Author: Yuan · JinSheng <br>* @Since 2024/3/27 18:18*/
@Configuration
public class SimpleQueueConfig {@BeanQueue simpleQueue() {return QueueBuilder.durable("simple_queue").build();}
}
2. 发布消费Controller
package com.happy.msg.publisher;import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;/*** <p>** @Description: 生产消息的控制器 <br>* </p>* @Datetime: 2024/3/27 18:53* @Author: Yuan · JinSheng <br>* @Since 2024/3/27 18:53*/
@RestController
@RequestMapping("/simple")
public class SimpleQueuePublisherController {@Autowiredprivate RabbitTemplate rabbitTemplate;@GetMapping("/send")public String sentMessage() {rabbitTemplate.convertAndSend("simple_queue", "hello,rabbitmq");return "ok";}
}
2. 消息消费者
package com.happy.msg.consumer;import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;import java.time.LocalDateTime;
/*** <p>* @Description: 简单队列_消息消费控制器 <br>* </p>* @Datetime: 2024/3/28 20:22* @Author: Yuan · JinSheng <br>* @Since 2024/3/28 20:22*/
@Slf4j
@Component
public class SimpleQueueConsumer {/**** @param message 消息* @Description: 监听simple_queue队列中的消息,当客户端启动后,simple_queue队列中的所有的消息都被此消费者消费并打印* @Author: Yuan · JinSheng*/@RabbitListener(queues = "simple_queue")public void msg(Message message){byte[] messageBody = message.getBody();String msg = new String(messageBody);log.info("接收到的消息==={},===接收时间==={}",msg, LocalDateTime.now());}
}
3. 输出结果
接收到的消息===hello,rabbitmq,===接收时间===2024-03-29T10:24:02.994453200
,msg, LocalDateTime.now());}
}