RabbitMQ 学习笔记 Spring Boot

RabbitMQ

image.png

工作模式

https://www.rabbitmq.com/getstarted.html

  • 简单模式:一个消费者
  • work模式:一个队列,多个消费者,多个消费者处理不同的任务
  • 订阅模式:引入了交换机(Fanout类型),交换机绑定多个队列,多个消费者,如果消息发送到没有队列绑定的交换机上,那么消息将丢失。
  • 路由模式:发送消息到交换机并且要指定路由key ,消费者将队列绑定到交换机时需要指定路由key
  • Topic模式:将路由键和某模式进行匹配,此时队列需要绑定在一个模式上

工作模式可以看成是订阅模式的简化(默认的交换机),多个消费端监听同一个队列不会重复消费消息
topic模式可以看成是路由模式的指定key使用了通配符替代。


image.png

交换机类型

交换机可以理解成具有路由表的路由程序,消息始终都是先发送到交换机,由交换级经过路由传送给队列,消费者再从队列中获取消息的

  • Direct 指定路由key,完全匹配
  • Fanout 广播,会转发到所有绑定此交换机的队列上
  • Topic 匹配路由键。# 匹配一个或多个词* 匹配一个词
  • Headers 与Topic类似,但路由值是基于消息的header数据。

安装

使用 docker-compose 安装,docker-compose的安装与部署,请移步 https://cchao1024.github.io/Docker解放生产力
docker-compose.yaml 下增加 RabbitMQ

version: "3.7"
services:
  rabbitmq:
    image: rabbitmq:management-alpine
    container_name: rabbitmq
    environment:
      - RABBITMQ_DEFAULT_USER=root               # 账号密码 可以自定义
      - RABBITMQ_DEFAULT_PASS=root
    restart: always
    ports:
      - "15672:15672"
      - "5672:5672"
    logging:
      driver: "json-file"
      options:
        max-size: "200k"
        max-file: "10"

通过 docker-compose up 启动完成后,通过浏览器访问 http://localhost:15672/
输入账号密码后即可进入RabbitMQ后台,

image.png

SpringBoot start

  1. 引入依赖

    org.springframework.boot
    spring-boot-starter-test
    test


    org.springframework.boot
    spring-boot-starter-amqp

  1. 获取消息队列
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(InsomniaApplication.class, args);
    }
    @Bean
    public Queue helloQueue() {
        return new Queue("hello");
    }
  1. 创建业务Service
@Component
public class MqService {
    @Autowired
    AmqpTemplate mRabbitTemplate;
    public static String mHelloQueue = "helloQueue";

    public void pushLikeEvent(int type, long toUserId) {
        String sendMsg = "hello1 " + new Date();
        System.out.println("Sender1 : " + sendMsg);
        mRabbitTemplate.convertAndSend(mHelloQueue, sendMsg);
    }
}
  1. 测试代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class MqServiceTest {
    @Autowired
    MqService mMqService;

    @Test
    public void pushLikeEvent() {
        for (int i = 0; i < 10; i++) {
            mMqService.pushLikeEvent();
        }
    }
}
  1. 消费者
@Component
@RabbitListener(queues = "hello")
@Slf4j
public class PushHandler {
    @Bean
    public Queue teaQueue() {
        return new Queue("hello");
    }

    @RabbitHandler
    public void process(@Payload String message) {
        log.info("Listener收到String类型mq消息:" + message);
    }

你可能感兴趣的:(RabbitMQ 学习笔记 Spring Boot)