RabbitMQ springboot 简单模式-生产者工程

上接:RabbitMQ springboot创建父工程

创建生产者子模块

在父项目中,创建生产者子模块:producer

略

pom.xml

由于父项目已引入所有依赖包,所以pom.xml中不做任何修改

application.yml

在 resources 目录下创建 application.yml 文件,内容如下:

server:
  port: 8081

spring:
  application:
    #服务名称
    name: rabbitmq-producer
  #RabbitMQ配置
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
    #虚拟host 可以不设置,使用server默认host
#    virtual-host: RabbitMqHost

创建 RabbitMQ配置类

生产者需要事先创建队列,然后才能发送消息,所以增加 配置类,启动时,自动创建 queue,这里是:notice

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

@Configuration
public class RabbitMQConfig {
    public static final String NOTICE="notice";
    @Bean
    public Queue createQueue(){
        //创建notice队列
        return new Queue(NOTICE,true);
    }
}

Queue构造方法参数说明,详见:RabbitMQ spring-boot-starter-amqp Queue类说明

创建 controller

import org.malaoshi.config.RabbitMQConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/")
public class ProducerController {
    @Resource
    private RabbitTemplate rabbitTemplate;


    @RequestMapping("/sendNotice")
    public String sendNotice(String msg){
        rabbitTemplate.convertAndSend(RabbitMQConfig.NOTICE, msg);

        return "【" + msg + "】 已发送!";
    }
}

主启动类

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

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

启动服务

启动主启动类

访问 rabbitmq web管理页面

访问 http://localhost:15672/ RabbitMQ管理页面,此时 没有 消息队列

这是因为 懒加载 方式,没不会创建队列

发送消息

访问 http://localhost:8081/sendNotice?msg=abc ,会发送消息,消息内容是 abc

访问 rabbitmq web管理页面

此时创建 消息队列 notice 了


原文出处:/show_1IX1ibza98bs.html