SpringBoot实战笔记:29_异步消息_02_AMQP_RabbitMQ

29_异步消息_02_AMQP_RabbitMQ

1,docker下运行 rabbitmq 镜像为容器
  • 5672 :消息代理的端口
  • 15672 :管理界面端口

开启虚拟机对上述两个端口的端口映射后,重启虚拟机(VMware Fusion Mac版本)

docker run -d -p 5672:5672 -p 15672:15672 rabbitmq:3-management

浏览器访问:http://localhost:15672/

2,新建 Spring Boot 项目
  • 依赖:AMQP(spring-boot-starter-amqp)
  • Spring Boot 默认我们的 Rabbit 主机为 localhost、端口号为 5672 ,所以我们无需为 Spring Bootapplication.properties 配置 RabbitMQ 的连接信息
3,定义要发送的信息及目的地(队列)
package com.zyf;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Springboot20Application implements CommandLineRunner{

    /**
     * Spring Boot 已经为我们配置好rabbitTemplate
     */
    @Autowired
    RabbitTemplate rabbitTemplate;

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

    /**
     * 定义目的地(队列),队列名称为:zyf-queue
     * @return
     */
    @Bean
    public Queue zyfQueue(){
        return new Queue("zyf-queue");
    }

    @Override
    public void run(String... strings) throws Exception {
        //向对列zyf-queue发送消息
        rabbitTemplate.convertAndSend("zyf-queue","来自RabbitMQ的消息:我是AMQP的实现");
    }
}
4,消息监听
package com.zyf;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Created by zyf on 2018/3/16.
 */
@Component
public class Receiver {

    /**
     * 注解@RabbitListener用来声明要监听哪个队列(目的地)
     * @param message
     */
    @RabbitListener(queues = "zyf-queue")
    public void receiveMessage(String message){
        System.out.println("Received <" + message + ">");
    }

}
5,运行

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值