springboot-rabbitmq之hello-world(一)

概念介绍

这里引用rabbit官网的一张图


image.png

大概意思就是生产者把消息发送到队列然后消费者消费消息

springboot实现

hello-world比较简单这里直接上代码

生产者

声明默认配置

@Component
@Data
public class MyBean {
    private final AmqpAdmin amqpAdmin;
    private final AmqpTemplate amqpTemplate;
    @Autowired
    public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
        this.amqpAdmin = amqpAdmin;
        this.amqpTemplate = amqpTemplate;
    }
  //声明一个队列springboot会自动绑定到默认的路由
    @Bean
    Queue queue(){
        return QueueBuilder.durable("hello").build();
    }
}

发送消息

    @Autowired
    MyBean myBean;
  //注意这里默认的routingkey为队列的名称,请和上面声明的队列保持一致
    @Test
    void msgSend(){
        myBean.getAmqpTemplate().convertAndSend("hello","hello-world!");
    }

感觉比不用springboot少了一大堆代码有没有...太简洁了

消费者

消费者就更简单了直接一句话

@Component
@Slf4j
public class ReceiverBean {
    @RabbitListener(queues = "hello")
    public void processMessage(String msg) {
        log.info("msg---"+msg);
    }
}

这里贴springboot手册关于rabbitmq的一段话


image.png

大概意思就是如果没有特殊的配置springboot会启用默认的工厂,接收消息直接用这个就可以了

其他

另外大家是不是发现我没有配置rabbit的用户名密码,如果是本机如果你用的是默认的用户名密码是不需要写的(guest:guest)

最后上代码

消费者/生产者
https://gitee.com/ethanlab/rabbitmq/tree/master/rabbit-helloworld-consumer
https://gitee.com/ethanlab/rabbitmq/tree/master/rabbit-helloworld-producer

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容