springboot整合rabbitmq发送消息

springboot整合rabbitmq发送消息

构建项目

image.png
  • 构建gradle
repositories {
   mavenCentral()
}

ext{
   springBootVersion = "2.0.3.RELEASE"
}
dependencies {

   compile("org.springframework.boot:spring-boot-starter-amqp:1.5.2.RELEASE")
   compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion")
   compile("org.springframework.boot:spring-boot-starter-undertow:$springBootVersion")



}
//排除tomcat
configurations {
   compile.exclude module: 'spring-boot-starter-tomcat'
}
  • 手动创建queues


    image.png
  • 生产者

@Component
public class DemoProducer {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String sendMsg = "msg " + new Date();
        System.out.println("生产者开始生产信息 : " + sendMsg);
        this.rabbitTemplate.convertAndSend("msg", sendMsg);
    }
}
  • 消费者
@Component
@RabbitListener(queues = "msg")
public class DemoReceiver {

   @RabbitHandler
   public void process(String msg) {
       System.out.println("消费者 收到信息  : " + msg);
   }
}

  • 测试controller
@Controller
@RequestMapping("/rabbit")
public class DemoController {

    @Autowired
    private DemoProducer demoProducer;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(HttpServletRequest request) {
        demoProducer.send();
        return "success";
    }
}
  • yml配置
spring:
  rabbitmq:
    host: ######
    port: ######
    username: ######
    password: ######
    virtual-host: /

server:
  port: 9000

你可能感兴趣的:(springboot整合rabbitmq发送消息)